我正在嘗試學習 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")
該代碼有效并且我的用戶代理已切換,但是現在發生了一個以前沒有發生的錯誤。網路驅動程式/瀏覽器(Chrome 驅動程式)在顯示網站一秒鐘后自動關閉,無需我指定driver.quit()引數。當我不切換我的用戶代理時,它不會關閉,除非我這樣做并且我想在關閉它之前稍微研究一下頁面。我試圖等待使用,time.sleep()但這不起作用。
如何使 webdriver 在指定之前不關閉?
非常感謝答案,最好帶有如何實作解決方案的代碼示例。
uj5u.com熱心網友回復:
我不確定問題是否與您正在使用的 webdriver 版本有關,但是當我嘗試time.sleep(n)在使用webdriver_manager庫下載最新版本時添加到您的代碼時,ChromeWebDriver我有機會查看網站和直到計時器完成,瀏覽器才關閉。
我的代碼:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
from webdriver_manager.chrome import ChromeDriverManager
import time
# 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(ChromeDriverManager().install(), chrome_options=options)
driver.get("https://www.whatismybrowser.com/detect/what-is-my-user-agent")
time.sleep(100)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406764.html
標籤:
