栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当使用Selenium WebDriver 加载页面时出现浏览器闪退时,如何解决?

Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样,今天在针对js动态网页爬虫时,使用代理并使用Selenium,打开网页时,浏览器总是一闪而退,代码如下:

from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
def chrome_proxy():
    driver_path = Service(r'C:Python39chromedriver.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:Python39chromedriver.exe')定义在函数外面确成功了,没有出现闪退,此时恍然大悟,是由于浏览器不是全局变量导致。

from selenium import webdriver

from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
driver_path = Service(r'C:Python39chromedriver.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 webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
def chrome_proxy():
    # 需要设置browser为全局变量才可以,否则会闪退
    global browser
    driver_path = Service(r'C:Python39chromedriver.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()

推荐一家好用的代理ip成功率挺高的:https://h.shenlongip.com/index?from=seller&did=h4Dmox

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号