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

如何在Google Colab中爬取动态网站?解决SessionNotCreatedException错误

解决Google Colab中Chrome WebDriver会话创建失败问题

问题根源

你的代码存在两个核心问题:

  1. 重复初始化WebDriver:全局已经用配置好的options初始化了driver,但函数内部又重新调用webdriver.Chrome()(未传入任何配置),导致启动的Chrome缺少Colab环境必需的参数。
  2. 未指定Chrome二进制文件路径:Colab中默认安装的Chromium浏览器路径需要显式指定,否则WebDriver无法找到可执行文件。

修复步骤

1. 安装Colab必需的依赖

先在Colab中执行以下命令安装Chromium和ChromeDriver:

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

2. 修正代码

调整后的代码解决了初始化问题并补充了必要配置:

from selenium import webdriver
from selenium.webdriver.common.by import By

def get_pubchem_ids(search_term):
    # 配置Chrome选项
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')  # 无头模式运行,无图形界面
    options.add_argument('--no-sandbox')  # 禁用沙箱,Colab环境必需
    options.add_argument('--disable-dev-shm-usage')  # 解决/dev/shm空间不足问题
    options.add_argument('--remote-debugging-port=9222')  # 避免DevToolsActivePort文件缺失报错
    options.binary_location = '/usr/bin/chromium-browser'  # 指定Colab中Chromium的安装路径

    # 初始化带完整配置的WebDriver
    driver = webdriver.Chrome(options=options)
    
    base_url = "https://pubchem.ncbi.nlm.nih.gov/"
    search_url = f"{base_url}#query={search_term}"
    
    driver.get(search_url)
    driver.implicitly_wait(10)  # 隐式等待元素加载完成

    # 定位目标元素
    elements = driver.find_elements(By.XPATH,'//a[@class="f-medium" and contains(@href, "compound")][@data-action="result-link"][@data-label="Result Secondary Link; Position:1; Page:1"]//span[@class="breakword"]/span')
    
    # 提取并打印结果(示例操作)
    if elements:
        pubchem_ids = [elem.text for elem in elements]
        print("提取到的PubChem ID:", pubchem_ids)
    else:
        print("未找到目标元素")
    
    driver.quit()

# 测试调用
get_pubchem_ids("aspirin")

关键配置说明

  • --no-sandbox:Colab虚拟机环境下,Chrome默认沙箱模式无法正常启动,必须禁用。
  • --disable-dev-shm-usage:Colab的/dev/shm分区空间有限,禁用后会使用临时文件替代,避免启动失败。
  • --remote-debugging-port=9222:强制指定调试端口,解决DevToolsActivePort file doesn't exist报错。
  • binary_location:显式指定Chromium的路径,确保WebDriver能正确找到浏览器可执行文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:13:40