我正在尝试学习 Selenium 来抓取一些 Javascript 繁重的网站。我可以很好地定位和提取信息。但是,我发现对于某些站点,我需要切换我的用户代理。我通过以下方式进行测试:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
PATH ="C:/my/path/to/chromedriver.exe"
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options = Options()
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=PATH)
driver.get("https://www.whatismybrowser.com/detect/what-is-my-user-agent")
代码有效,我的用户代理已切换,但是现在出现了一个以前没有出现过的错误。在我没有指定 driver.quit()
参数的情况下,webdriver/browser(Chrome 驱动程序)在显示网站一秒钟后自动关闭。当我不切换我的用户代理时,它不会关闭,除非我这样做并且我想在关闭它之前稍微研究一下页面。我尝试使用 time.sleep()
等待,但这不起作用。
如何让 webdriver 在指定之前不关闭?
非常感谢您的回答,最好是带有如何实现该解决方案的代码示例。
最佳答案
这应该对你很好:
options.add_experimental_option("detach", True)
在您的代码中:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
PATH ="C:/my/path/to/chromedriver.exe"
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options = Options()
options.add_argument(f'user-agent={userAgent}')
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(chrome_options=options, executable_path=PATH)
driver.get("https://www.whatismybrowser.com/detect/what-is-my-user-agent")
https://stackoverflow.com/questions/70639403/