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

GitHub Codespaces中Python Selenium+ChromeDriver爬虫启动失败求助

解决GitHub Codespaces中Selenium Chrome启动失败问题

步骤1:清理冲突的旧包

先卸载apt安装的旧版chromium相关包,避免和snap要求冲突:

sudo apt remove -y chromium-browser chromium-chromedriver python3-selenium

步骤2:修改Python代码,利用chromedriver-binary自动管理驱动

你已经通过pip安装了chromedriver-binary,它会自动将兼容的chromedriver加入系统PATH,无需手动指定驱动路径。同时补充必要的Chrome参数,确保在Codespaces环境中稳定运行:

import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

class PriceScraper:
    def scrape(self):
        input_url = "https://www.google.com"
        chrome_options = Options()
        # 使用Selenium 4+推荐的无头模式
        chrome_options.add_argument("--headless=new")
        # 解决Codespaces环境资源限制问题
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--no-sandbox")
        # 指定chromium二进制文件路径
        chrome_options.binary_location = "/usr/bin/chromium"
        # 无需手动创建Service,chromedriver-binary会自动匹配驱动
        driver = webdriver.Chrome(options=chrome_options)
        try:
            driver.get(input_url)
            # 这里添加你的爬取逻辑
            print("页面标题:", driver.title)
        finally:
            # 确保驱动退出
            driver.quit()

if __name__ == '__main__':
    scraper = PriceScraper()
    scraper.scrape()

步骤3:安装新版chromium(若未安装)

执行以下命令安装apt仓库中的新版chromium:

sudo apt update && sudo apt install -y chromium

问题原因说明

  1. 旧包冲突:你安装的chromium-browser是旧版废弃包,对应的chromium-chromedriver会强制要求使用snap版chromium,但GitHub Codespaces默认未启用snapd服务,导致无法安装。
  2. 驱动不兼容:手动指定/usr/bin/chromedriver使用的是apt旧版驱动,与你通过pip安装的chromedriver-binary提供的新驱动冲突,导致Chrome启动失败。
  3. 无头模式参数过时:旧的--headless参数在新版Chrome中稳定性不足,改用--headless=new可避免DevToolsActivePort相关错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:12:47