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

Jupyter Notebook正常运行的ChromeDriver代码在JupyterLab报错,如何修复?

问题修复方案:JupyterLab中Selenium ChromeDriver报错

核心问题分析

你的代码在JupyterLab中报错,大概率是ChromeDriver路径未正确配置或Selenium版本与ChromeDriver/Chrome浏览器版本不兼容导致的——JupyterLab的环境变量加载逻辑和Notebook略有差异,直接调用webdriver.Chrome(options)可能无法找到驱动文件。

修复方法

方法1:手动指定ChromeDriver绝对路径

安装chromium-chromedriver后,驱动文件通常位于/usr/bin/chromedriver,通过ChromeService明确指定路径即可:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions

options = ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# 手动指定chromedriver路径
service = ChromeService(executable_path='/usr/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=options)

方法2:正确使用ChromeDriverManager(适配Selenium 4+)

若之前使用ChromeDriverManager的方式错误,需配合ChromeService调用,确保自动下载的驱动与本地Chrome版本匹配:

先安装ChromeDriverManager:

!pip install webdriver-manager

再修改代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from webdriver_manager.chrome import ChromeDriverManager

options = ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# 自动匹配并下载对应版本的ChromeDriver
service = ChromeService(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)

方法3:验证版本兼容性

执行以下命令检查Chrome浏览器和ChromeDriver版本,确保两者主版本号一致(比如都是118.x):

# 检查Chrome版本
!google-chrome --version
# 检查ChromeDriver版本
!chromedriver --version

若版本不匹配,卸载现有chromedriver并重新安装对应版本:

!apt remove chromium-chromedriver
!apt install chromium-chromedriver=118.0.5993.70-0ubuntu0.20.04.1  # 替换为与Chrome匹配的版本号

其他JupyterLab中使用ChromeDriver的替代方案

  • 切换至Firefox GeckoDriver:若ChromeDriver问题持续,可尝试使用Firefox,安装命令和代码如下:
    !apt-get install firefox
    !pip install webdriver-manager
    
    from selenium import webdriver
    from selenium.webdriver.firefox.service import Service as FirefoxService
    from selenium.webdriver.firefox.options import Options as FirefoxOptions
    from webdriver_manager.firefox import GeckoDriverManager
    
    options = FirefoxOptions()
    options.add_argument('--headless')
    service = FirefoxService(GeckoDriverManager().install())
    driver = webdriver.Firefox(service=service, options=options)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:07:09