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

使用Selenium获取亚马逊商品价格返回空值问题求助

解决Selenium爬取亚马逊商品价格返回空值的问题

问题场景

爬取亚马逊商品页面(链接:https://www.amazon.com/dp/B00M0DWQYI?th=1)时,无法获取商品价格,返回空值,原代码如下:

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd


url='https://www.amazon.com/dp/B00M0DWQYI?th=1'
PATH="C:\\Program Files (x86)\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get(url)
item=dict()
try:
    item['price'] = driver.find_element(By.XPATH, "//div[@id='corePrice_feature_div'] //span[@class='a-offscreen']").text
except:
    item['price']=''    
print(item)

解决方案

  • 添加显式等待:页面加载需要时间,直接获取元素可能还未渲染完成,用WebDriverWait等待元素出现后再执行获取操作。
  • 配置浏览器反检测选项:亚马逊会识别Selenium自动化特征,通过设置浏览器参数规避检测,比如禁用自动化提示、设置真实用户代理。
  • 优化元素定位逻辑:确认XPath定位的准确性,若页面结构变动,可调整为更稳定的属性组合定位(比如结合多个元素层级属性)。
  • 完善异常捕获:捕获具体异常并打印错误信息,方便排查问题根源。

修改后的代码示例

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

url = 'https://www.amazon.com/dp/B00M0DWQYI?th=1'
PATH = "C:\\Program Files (x86)\\chromedriver.exe"

# 配置浏览器选项,规避反爬检测
chrome_options = Options()
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")

driver = webdriver.Chrome(PATH, options=chrome_options)
driver.get(url)
item = dict()

try:
    # 显式等待价格元素加载,最长等待10秒
    price_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//div[@id='corePrice_feature_div']//span[@class='a-offscreen']"))
    )
    item['price'] = price_element.text
except Exception as e:
    print(f"获取价格失败: {str(e)}")
    item['price'] = ''

print(item)
driver.quit()

额外排查方向

如果上述修改后仍无法获取价格,可尝试:

  • 检查是否需要登录亚马逊账号(部分商品价格仅对登录用户展示)
  • 更换IP地址,避免被亚马逊IP限制
  • 模拟滚动页面,触发价格模块的动态加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:15:58