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

本文介绍了使用Selenium进行网页爬取时遇到的问题及解决方法,特别是如何正确配置代理以避免浏览器打开后立即关闭的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:\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 webdriver
from selenium.webdriver.chrome.service import Service
driver_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 webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
def 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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非凡的小羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值