当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决? |
您所在的位置:网站首页 › dreamweaver打开闪退 › 当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决? |
Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样,今天在针对js动态网页爬虫时,使用代理并使用Selenium,打开网页时,浏览器总是一闪而退,代码如下: from selenium import webdriverfrom seleniumwire import webdriverfrom selenium.webdriver.chrome.service import Servicedef chrome_proxy(): driver_path = Service(r'C:\Python39\chromedriver.exe') chromeoptions = webdriver.ChromeOptions() # 设置代理 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() 然后以为是下载的浏览器驱动版本不同导致。所以我第一步先排查我的浏览器版本, 如图1:(版本为102.0.5005.63) 浏览器驱动版本我下载的是102.0.5005.61并放到了python的安装目录下(不能用103.0.5060.24会报错版本不匹配): (下载地址:http://chromedriver.storage.googleapis.com/index.html) 但是版本已经相同了,浏览器还是一闪而退,并且也没有报错驱动版本的错误,但是无意中把driver_path = Service(r'C:\Python39\chromedriver.exe')定义在函数外面确成功了,没有出现闪退,此时恍然大悟,是由于浏览器不是全局变量导致。 from selenium import webdriver from seleniumwire import webdriverfrom selenium.webdriver.chrome.service import Servicedriver_path = Service(r'C:\Python39\chromedriver.exe')def chrome_proxy(): chromeoptions = webdriver.ChromeOptions() # 设置代理 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 webdriverfrom seleniumwire import webdriverfrom selenium.webdriver.chrome.service import Servicedef chrome_proxy(): # 需要设置browser为全局变量才可以,否则会闪退 global browser driver_path = Service(r'C:\Python39\chromedriver.exe') chromeoptions = webdriver.ChromeOptions() # 设置代理 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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |