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

如何使用Selenium不启动Chrome浏览器爬取亚马逊商品价格?

问题解决指南

你当前的报错和需求可以通过修正元素定位逻辑、配置Chrome无头模式两个核心操作解决:

错误原因说明

  • find_element_by_class_name 方法仅支持传入单个类名,你传入的a-section a-spacing-micro是两个类名,因此解析器会识别为错误的选择器,无法匹配到对应元素
  • 默认启动的Chrome会弹出浏览器窗口,需要额外配置无头参数实现后台静默运行
  • 未添加等待逻辑,很可能出现页面还未加载完成就执行元素定位的情况,也会触发找不到元素的报错
  • 未配置请求头伪装,容易被亚马逊反爬机制拦截,返回无目标元素的空白页面

完整修正代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 配置Chrome运行参数
chrome_options = Options()
# 开启无头模式,不会弹出浏览器窗口
chrome_options.add_argument("--headless")
# 禁用GPU,避免无头模式出现兼容性异常
chrome_options.add_argument("--disable-gpu")
# 伪装浏览器UA,绕过基础反爬检测
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36")
# 固定窗口尺寸,避免无头模式下元素定位错位
chrome_options.add_argument("--window-size=1920,1080")

# 启动驱动,替换为你本地的chromedriver路径
driver = webdriver.Chrome('C:/Users/musta/Desktop/chromedriver.exe', options=chrome_options)
driver.get("https://www.amazon.com/dp/b07h9fldcd")

try:
    # 显式等待最多10秒,直到目标元素加载完成
    price_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".a-section.a-spacing-micro"))
    )
    get_text = price_element.get_attribute("textContent").strip()
    print(f"抓取到的价格信息:{get_text}")
except Exception as e:
    print(f"定位失败:{e}")
finally:
    driver.quit()

额外注意事项

  • 如果仍然定位失败,大概率是触发了亚马逊的人机验证,可以尝试添加代理IP、调整请求间隔,也可以换用requests+BeautifulSoup的轻量方案,不需要启动浏览器性能更高
  • 多类名元素使用CSS选择器定位时,每个类名前加.,类名之间不要留空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:15:03