Google Colab中chromedriver意外退出(状态码1)问题求助
解决Google Colab中Chromedriver意外退出(状态码1)的问题
问题场景
在Google Colab运行Python Selenium爬虫时,原本正常的代码突然报出WebDriverException,提示chromedriver意外退出,状态码为1。
报错信息
WebDriverException Traceback (most recent call last) <ipython-input-9-4595cedc713a> in <module> 6 options.add_argument('--no-sandbox') 7 options.add_argument('--disable-dev-shm-usage') ----> 8 wd = webdriver.Chrome('chromedriver',options = options) 3 frames /usr/local/lib/python3.8/dist-packages/selenium/webdriver/common/service.py in assert_process_still_running(self) 117 return_code = self.process.poll() 118 if return_code: ---> 119 raise WebDriverException(f"Service {self.path} unexpectedly exited. Status code was: {return_code}") 120 121 def is_connectable(self) -> bool: WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 1
原代码
!apt-get update !apt install -y chromium-chromedriver !cp /usr/lib/chromium-browser/chromedriver /usr/bin !pip install selenium from selenium import webdriver from selenium.webdriver.common.by import By options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') wd = webdriver.Chrome('chromedriver',options = options)
解决方案
核心修正点
- 适配新版Selenium驱动初始化方式:旧版直接传入驱动路径的写法已被弃用,改用
Service类管理驱动服务,避免路径识别错误。 - 更新Headless模式参数:新版Chrome推荐使用
--headless=new参数,替代旧的--headless,提升兼容性。 - 明确驱动路径:指定
/usr/bin/chromedriver完整路径,避免系统找不到驱动文件。
修正后的代码
!apt-get update !apt install -y chromium-chromedriver !cp /usr/lib/chromium-browser/chromedriver /usr/bin !pip install selenium from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By options = webdriver.ChromeOptions() options.add_argument('--headless=new') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') # 使用Service类指定驱动路径 service = Service('/usr/bin/chromedriver') wd = webdriver.Chrome(service=service, options=options)
额外排查方案
如果上述修正后仍报错,可尝试重新安装匹配版本的Chromium和Chromedriver,避免版本不兼容:
!apt-get remove -y chromium-chromedriver !apt-get install -y chromium-chromedriver=114.0.5735.90-0ubuntu0.20.04.1
内容的提问来源于stack exchange,提问作者FHAlex
相关产品推荐
相关产品推荐

