两个相同Selenium项目仅一个可运行WebDriver的问题求助
问题场景
两个配置、代码完全一致的Selenium项目,其中一个可正常启动浏览器,另一个出现异常:
- 使用代码
driver = webdriver.Chrome()时,报错:
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.
- 指定chromedriver绝对路径后(
driver = webdriver.Chrome(r"C:\Users\user\PycharmProjects\Sel\chromedriver.exe")),报错:
ValueError: Timeout value connect was <object object at 0x0000022461CC8720>, but it must be an int, float or None.
已确认使用最新版本Selenium,完整测试代码如下:
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(r"C:\Users\user\PycharmProjects\Sel\chromedriver.exe") driver.get('https://the-internet.herokuapp.com/drag_and_drop') driver.implicitly_wait(10)
可能原因及解决方法
Python环境依赖不一致:两个项目看似配置相同,实际可能使用不同虚拟环境,导致依赖版本冲突(尤其是
urllib3)。
解决:分别在两个项目环境中执行pip list,对比selenium、urllib3等依赖版本。若urllib3版本过高,可降级至1.26.x~1.27.x区间,执行命令:pip install urllib3==1.26.15。Chromedriver与Chrome版本不匹配:当前项目中的chromedriver版本和本地Chrome浏览器版本不兼容,而正常项目中的chromedriver是匹配的。
解决:查看Chrome浏览器版本(设置→关于Chrome),下载对应版本的chromedriver替换当前项目中的文件。初始化方式兼容性问题:最新Selenium推荐使用
Service类管理驱动,旧的直接传路径方式可能存在兼容问题。
解决:修改代码为:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC service = Service(r"C:\Users\user\PycharmProjects\Sel\chromedriver.exe") driver = webdriver.Chrome(service=service) driver.get('https://the-internet.herokuapp.com/drag_and_drop') driver.implicitly_wait(10)
- 虚拟环境异常:当前项目的虚拟环境存在损坏或配置错误。
解决:删除现有虚拟环境,重新创建并安装最新Selenium依赖后测试。
内容的提问来源于stack exchange,提问作者Mlomow

