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

使用Selenium通过class属性提取商品价格失败,部分产品无法获取,求排查

问题原因与解决方案

为什么拿不到价格?

你用的.a-offscreen元素是亚马逊用来隐藏文本的(通常通过CSS定位到视口外),Selenium的.text属性只会返回可见元素的文本内容,所以隐藏元素的.text会是空字符串。

解决方法

有两种可靠的方式获取价格:

方法1:获取元素的textContent属性

直接读取元素的textContent属性,不管元素是否可见都能拿到文本:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)

driver.get('https://www.amazon.in/Nothing-Phone-Black-128-RAM/dp/B0BKZVF7VV/ref=sr_1_2?crid=2V22OHL4YXGHF&keywords=nothing+phone+1&qid=1678089940&sprefix=nothing%2Caps%2C209&sr=8-2')

price_element = driver.find_element(By.CLASS_NAME, "a-offscreen")
# 使用get_attribute获取textContent
print(price_element.get_attribute("textContent"))

driver.quit()

方法2:定位可见的价格元素

亚马逊商品页面的可见价格通常拆分在整数和小数部分,或者包含在统一的可见容器里,直接定位这些可见元素更稳定:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)

driver.get('https://www.amazon.in/Nothing-Phone-Black-128-RAM/dp/B0BKZVF7VV/ref=sr_1_2?crid=2V22OHL4YXGHF&keywords=nothing+phone+1&qid=1678089940&sprefix=nothing%2Caps%2C209&sr=8-2')

# 定位可见的价格整数部分
price_whole = driver.find_element(By.CSS_SELECTOR, "span.a-price-whole").text
# 定位价格小数部分
price_fraction = driver.find_element(By.CSS_SELECTOR, "span.a-price-fraction").text
# 拼接完整价格
print(f"{price_whole}.{price_fraction}")

driver.quit()

补充说明

你之前能用同一个class拿到部分产品价格,大概率是那些页面的.a-offscreen元素实际是可见的(或亚马逊页面结构存在差异),但这个class本质是用于隐藏文本的,不推荐作为稳定定位方式,优先选择可见元素更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:15:32