You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Colab中使用Selenium启动失败的问题求助

背景

在MacOS上运行Selenium时遇到诸多问题,因此转到Google Colab尝试运行。

当前情况

尝试了几天前用过的解决方案,但依旧无法打开网站。

代码

依赖安装命令

!pip install selenium
!apt-get update 
!apt install chromium-chromedriver
!apt-get install -y chromium-browser

Python运行代码

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait

options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver',options=options)

错误信息

/usr/local/lib/python3.8/dist-packages/selenium/webdriver/common/service.py 在 assert_process_still_running(self) 方法中:
    115         return_code = self.process.poll()
    116         if return_code:
--> 117             raise WebDriverException(f"Service {self.path} 意外退出。状态码:{return_code}")
    118 
    119     def is_connectable(self) -> bool:

WebDriverException: 错误信息:Service /usr/bin/chromedriver 意外退出。状态码:1

解决方案

1. 规范依赖安装流程

Chrome浏览器与chromedriver版本不匹配是常见诱因,按以下顺序重新安装可确保版本兼容:

!apt-get update
!apt-get install -y chromium-browser
!apt-get install -y chromium-chromedriver
!pip install selenium==4.8.3  # 指定适配Colab环境的稳定版本

2. 修正代码问题

  • 补充缺失的webdriver导入
  • 改用Selenium 4+推荐的Service类管理驱动
  • 更新无头模式参数,避免兼容性问题
  • 确认驱动路径与实际位置一致

修正后的完整代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait

options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless=new')  # 适配Selenium 4的无头模式
options.add_argument('--disable-gpu')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--remote-debugging-port=9222')  # 规避端口占用冲突

# 确认驱动实际路径后替换,或用which chromedriver命令查询
service = Service('/usr/lib/chromium-browser/chromedriver')
driver = webdriver.Chrome(service=service, options=options)

# 测试访问网站
try:
    driver.get("https://www.google.com")
    print("页面标题:", driver.title)
finally:
    driver.quit()

3. 验证驱动路径

错误提示中驱动路径为/usr/bin/chromedriver,但代码中指定的是/usr/lib/chromium-browser/chromedriver,可通过以下命令确认实际路径:

!which chromedriver

若输出为/usr/bin/chromedriver,则修改代码中Service的路径参数即可。


内容的提问来源于stack exchange,提问作者kinslersi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:55:32