使用Selenium的无头模式下,出现了DevTools连接断开的问题:

报错如下所示:

self =

response = {'status': 500, 'value': '{"value":{"error":"disconnected","message":"disconnected: not connected to DevTools\\n (fai...unk [0x75EA6BA9+25]\\n\\tRtlGetFullPathName_UEx [0x77588F9F+1215]\\n\\tRtlGetFullPathName_UEx [0x77588F6D+1165]\\n"}}'}

selenium.common.exceptions.WebDriverException: Message: disconnected: not connected to DevTools

以上问题属于DevTools连接超时自动中断了,可能出现的问题:

1. 版本不匹配:Selenium与浏览器或驱动程序的版本可能不兼容。请确保使用的Selenium版本与浏览器和驱动程序的版本相匹配。

2. 驱动程序问题:检查所使用的浏览器驱动程序是否正确安装和配置。确保驱动程序与所使用的浏览器版本兼容,并且在运行脚本之前已正确启动。

3. 网络问题:确保网络连接正常,没有任何防火墙或代理设置干扰与浏览器的通信。

4. 其他问题:暂未找到可能出现的其他原因,可以通过不同浏览器火狐、edge等看看是否重现。

我这边的出现的问题在调用webdriver自带的刷新方法时中断连接

def page_refresh_all(self):

"""

整个页面刷新,全页面

:return:

"""

self.driver.refresh()

time.sleep(2)

解决方案:

前置:当浏览器版本与驱动版本一致时,若不一致同步更新一致

1、增加连接超时时间:在创建浏览器实例时,增加连接超时时间。设置desired_capabilities增加连接超时时间: 设置的3秒可增加时间。

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()

chrome_options.add_argument('--headless')

desired_capabilities = chrome_options.to_capabilities()

desired_capabilities['pageLoadStrategy'] = 'none'

desired_capabilities['timeouts'] = {'implicit': 3000, 'pageLoad': 3000, 'script': 3000}

driver = webdriver.Chrome(desired_capabilities=desired_capabilities)

2、禁用沙盒模式:启用无头模式时,谷歌浏览器会在沙盒模式下运行,这会导致DevTools连接断开。尝试禁用沙盒模式,看看是否能够解决问题。在创建浏览器实例时,可以通过设置chromeOptions来禁用沙盒模式:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()

chrome_options.add_argument('--headless')

chrome_options.add_argument('--no-sandbox')

driver = webdriver.Chrome(chrome_options=chrome_options)

3、禁用插件:其他可能的冲突:其他正在运行的程序或插件可能会干扰Selenium与DevTools之间的通信,关闭其他可能干扰的程序或插件。

options.add_argument("--disable-extensions")

4、对代码中断部分添加异常处理。

def page_refresh_all(self):

"""

整个页面刷新,全页面

:return:

"""

time.sleep(1)

try:

# 判断是否已经连接到DevTools,如果未连接则重新建立连接

self.driver.execute('Browser.getVersion', {})

except Exception as e:

# 如果连接断开,则重新创建浏览器实例

self.driver.quit()

# 在重新创建浏览器实例之前,可以添加一些等待时间或其他处理

time.sleep(3)

self.driver = webdriver.Chrome()

# 可以设置其他的浏览器选项,例如设置无头模式、添加启动参数等

# self.driver = webdriver.Chrome(options=chrome_options)

self.driver.refresh()

time.sleep(2)

文章来源

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: