Google Colab中Selenium Chrome WebDriver运行报错咨询
问题原因与解决方案
为什么突然报错?
这是因为Selenium版本更新(从3.x升级到4.x+)后,webdriver.Chrome()的构造函数参数结构发生了变化:
- 在Selenium 3.x中,
webdriver.Chrome()的第一个位置参数是executable_path(驱动路径),所以你之前写webdriver.Chrome("chromedriver", options=options)是合法的。 - 但在Selenium 4.x+中,构造函数的第一个参数变成了
service(驱动服务对象),不再支持直接把驱动路径作为位置参数传递。此时你传入的"chromedriver"会被当成service参数,后面又显式传了options=options,就会触发"got multiple values for argument 'options'"的错误——因为新版本里,options只能作为关键字参数传递,但旧写法的位置参数会干扰参数解析。
正确的写法
方法1:直接省略驱动路径(推荐)
因为你已经在Colab中安装了chromium-driver,系统环境变量能自动找到驱动文件,所以不需要手动指定路径,直接写:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import WebDriverException try: url = "http://example.com/" options = Options() options.add_argument("--headless") options.add_argument("--no-sandbox") # 省略驱动路径,自动查找 driver = webdriver.Chrome(options=options) driver.get(url) print(driver.title) driver.quit() except WebDriverException as e: print(str(e))
方法2:显式指定驱动路径(用Service类)
如果确实需要手动指定驱动路径,需要使用selenium.webdriver.chrome.service.Service类:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.common.exceptions import WebDriverException try: url = "http://example.com/" options = Options() options.add_argument("--headless") options.add_argument("--no-sandbox") # 用Service类包装驱动路径 service = Service("chromedriver") driver = webdriver.Chrome(service=service, options=options) driver.get(url) print(driver.title) driver.quit() except WebDriverException as e: print(str(e))
为什么之前能运行?
你之前的脚本运行正常,是因为当时Colab环境中的Selenium版本还是3.x,参数规则和新版本不同。而你后来执行了!pip3 install -U selenium命令,把Selenium升级到了4.x+,导致参数规则变化,旧写法不再兼容。
内容的提问来源于stack exchange,提问作者user21848941
相关产品推荐
相关产品推荐

