本文介绍下载与Chrome浏览器的版本相匹配的ChromeDriver的两种方法。

一、问题场景

  Selenium是一个广泛使用的Web自动化测试工具,配合ChromeDriver使用,可以通过Python控制Chrome浏览器模拟各种用户操作。阿猪之前使用一直都正常,但是今天在运行时却出现如下报错信息:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 114
Current browser version is 116.0.5845.97 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe

  根据报错信息,是Chrome浏览器的版本超过了ChromeDriver支持的版本,可能是Chrome浏览器自动升级后导致的。要解决这个问题,可以手工下载对应版本的ChromeDriver,或者使用webdriver-manager自动管理ChromeDriver的版本。

二、手工下载对应版本的ChromeDriver

1、打开ChromeDriver的下载页面,下载与Chrome浏览器对应的版本。
  对于114及以下的版本,可以在这个页面下载,对于115及以上的版本,可以在Chrome for Testing availability页面下载

2、在python代码中指定ChromeDriver的路径。
  以Window为例,示例代码如下:

1
2
3
from selenium import webdriver

obj_page = webdriver.Chrome(executable_path='<chromedriver文件的路径>') # 创建一个WebDriver实例,并指定ChromeDriver的路径

如果是Linux环境,需要确保ChromeDriver文件具有执行权限,否则可能会遇到如下报错:

Traceback (most recent call last):
File “/home/zhu/Documents/liepin/main.py”, line 499, in
obj_page = webdriver.Chrome(service=chrome_service, options=obj_option)
File “/home/zhu/zhu-env/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py”, line 45, in init
super().init(
File “/home/zhu/zhu-env/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py”, line 50, in init
self.service.start()
File “/home/zhu/zhu-env/lib/python3.10/site-packages/selenium/webdriver/common/service.py”, line 98, in start
self._start_process(self._path)
File “/home/zhu/zhu-env/lib/python3.10/site-packages/selenium/webdriver/common/service.py”, line 230, in _start_process
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver-linux64-122.0.6261.128’ executable may have wrong permissions.

需要在终端中使用以下命令为文件添加执行权限:

1
chmod +x <chromedriver文件的路径>

三、使用webdriver-manager自动管理ChromeDriver的版本

1、安装webdriver

1
pip install webdriver-manager

2、在python中引用webdriver-manager
  以Window为例,示例代码如下:

1
2
3
4
5
6
7
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager

str_driver_path = ChromeDriverManager().install() # 匹配对应的ChromeDriver版本,并返回对应ChromeDriver的路径
chrome_service = ChromeService(str_driver_path) # 转换为ChromeService对象
obj_page = webdriver.Chrome(service=chrome_service) # 创建一个WebDriver实例