当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决?
Selenium是一個用于Web應(yīng)用程序測試的工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣,今天在針對js動態(tài)網(wǎng)頁爬蟲時,使用代理并使用Selenium,打開網(wǎng)頁時,瀏覽器總是一閃而退,代碼如下:
from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
def chrome_proxy():
????driver_path = Service(r'C:\Python39\chromedriver.exe')
????chromeoptions = webdriver.ChromeOptions()
????# 設(shè)置代理
????chromeoptions.add_argument("--proxy-server=http://223.242.228.140:42662")
????browser = webdriver.Chrome(service=driver_path,options=chromeoptions)
????# response = browser.get("http://myip.ipip.net")
????browser.get("https://www.baidu.com/")
????print("返回頁面", browser.page_source)
if __name__ == '__main__':
????chrome_proxy()
然后以為是下載的瀏覽器驅(qū)動版本不同導(dǎo)致。所以我第一步先排查我的瀏覽器版本,
如圖1:(版本為102.0.5005.63)
瀏覽器驅(qū)動版本我下載的是102.0.5005.61并放到了python的安裝目錄下(不能用103.0.5060.24會報錯版本不匹配):
(下載地址:http://chromedriver.storage.googleapis.com/index.html)
?
但是版本已經(jīng)相同了,瀏覽器還是一閃而退,并且也沒有報錯驅(qū)動版本的錯誤,但是無意中把driver_path = Service(r'C:\Python39\chromedriver.exe')定義在函數(shù)外面確成功了,沒有出現(xiàn)閃退,此時恍然大悟,是由于瀏覽器不是全局變量導(dǎo)致。
from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
driver_path = Service(r'C:\Python39\chromedriver.exe')
def chrome_proxy():
????chromeoptions = webdriver.ChromeOptions()
????# 設(shè)置代理
????chromeoptions.add_argument("--proxy-server=http://223.242.228.140:42662")
????browser = webdriver.Chrome(service=driver_path,options=chromeoptions)
????# response = browser.get("http://myip.ipip.net")
????browser.get("https://www.baidu.com/")
????print("返回頁面", browser.page_source)
因此也可以改寫成global browser定義成全局變量:
from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
def chrome_proxy():
????# 需要設(shè)置browser為全局變量才可以,否則會閃退
????global browser
????driver_path = Service(r'C:\Python39\chromedriver.exe')
????chromeoptions = webdriver.ChromeOptions()
????# 設(shè)置代理
????chromeoptions.add_argument("--proxy-server=http://223.242.228.140:42662")
????browser = webdriver.Chrome(service=driver_path,options=chromeoptions)
????# response = browser.get("http://myip.ipip.net")
????browser.get("https://www.baidu.com/")
????print("返回頁面", browser.page_source)
if __name__ == '__main__':
????chrome_proxy()
我用的代理是:https://h.shenlongip.com/index?from=seller&did=h4Dmox
總結(jié)
以上是生活随笔為你收集整理的当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4.Rabbits and Recurr
- 下一篇: JavaScript基础第05天笔记