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

Selenium无法通过CSS Selector/XPath爬取内容及Colab超时异常求助

问题分析与解决方案

核心问题判断

页面显示“Just a moment...”是Cloudflare人机验证拦截,这是导致XPath/CSS选择器返回空列表、Colab环境超时的根本原因——本地VSCode能正常运行,是因为本地浏览器已有验证通过的会话Cookie,而Colab属于全新环境,直接触发了反爬验证机制。

具体解决步骤

1. 绕过Cloudflare验证(本地/Colab通用)

使用undetected-chromedriver替代标准Selenium驱动,它能模拟真实浏览器行为,规避大部分Cloudflare检测:

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器(Colab需配置无头模式)
options = uc.ChromeOptions()
if 'google.colab' in str(get_ipython()):
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')

driver = uc.Chrome(options=options)
driver.get('https://www.ternbicycles.com/us/bikes#')

# 等待产品标题加载(替换为实际匹配的选择器)
wait = WebDriverWait(driver, 30)
titles = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.product-card__title')))

# 提取标题文本
for title in titles:
    print(title.text)

driver.quit()

Colab环境需先安装依赖:

!pip install undetected-chromedriver selenium

2. 确认选择器有效性

打开目标页面,按F12进入开发者工具,用元素选择器定位产品标题,复制正确的CSS选择器或XPath。避免使用过于泛化的选择器,确保能精准匹配目标元素(比如实际页面中产品标题的CSS类可能是.product-title,对应XPath为//h3[@class='product-title'])。

3. Colab环境超时优化

  • 延长等待时间:将WebDriverWait的超时时间从默认10秒调整为30-60秒,给Cloudflare验证和页面加载留足时间。
  • 配置容器适配参数:Colab中必须启用无头模式,同时添加--no-sandbox和--disable-dev-shm-usage参数,避免Chrome在容器环境中崩溃。

4. 备用方案:直接调用API

如果反爬拦截过于严格,可抓包获取产品数据接口,直接用requests调用接口获取数据,无需模拟浏览器:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
# 替换为实际抓包到的产品列表API地址
response = requests.get('https://www.ternbicycles.com/api/us/products', headers=headers)
products = response.json()
for product in products:
    print(product['title'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:45:33