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

亚马逊价格爬取报错:'NoneType'对象无get_text属性,偶现正常输出

解决亚马逊商品价格爬虫的AttributeError问题

问题原因

你遇到的AttributeError: 'NoneType' object has no attribute 'get_text',是因为亚马逊反爬机制拦截了部分请求,导致返回的页面中找不到a-price-whole元素(返回None),此时调用get_text()就会触发报错;偶尔成功是因为少数请求未被反爬规则拦截。

解决方案

1. 增加元素存在性判断,避免程序崩溃

在调用get_text()前,先检查元素是否存在,防止None类型报错。

2. 强化反爬规避策略

  • 使用requests.Session()维持会话,模拟浏览器持续连接状态
  • 添加请求重试机制,遇到请求失败(如5xx、429)时自动重试
  • 扩展请求头信息,让请求更接近真实浏览器行为
  • 提前检测是否被重定向到人机验证页面

3. 优化元素定位逻辑

通过先定位价格容器(a-price),再从中提取价格整数和小数部分,比直接定位a-price-whole更稳定。

修改后的完整代码

import requests
from bs4 import BeautifulSoup
import lxml
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

URL = 'https://www.amazon.com/dp/B075CYMYK6?ref_=cm_sw_r_cp_ud_ct_FM9M699VKHTT47YD50Q6&th=1'
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 Edg/118.0.2088.24",
    "Accept-Language": "en-US,en;q=0.9",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, br"
}

# 配置会话与重试策略
session = requests.Session()
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)

try:
    response = session.get(URL, headers=headers)
    # 检查是否触发人机验证
    if "captcha" in response.url or "verify" in response.url:
        print("触发人机验证,请调整请求头或使用代理")
    else:
        soup = BeautifulSoup(response.content, "lxml")
        # 分层定位价格元素
        price_container = soup.find(class_="a-price")
        if price_container:
            price_whole = price_container.find(class_="a-price-whole")
            price_fraction = price_container.find(class_="a-price-fraction")
            if price_whole and price_fraction:
                full_price = f"${price_whole.get_text()}{price_fraction.get_text()}"
                print(full_price)
            else:
                print未找到价格整数/小数部分")
        else:
            print("未找到价格容器")
except Exception as e:
    print(f"请求出错: {str(e)}")

代码说明

  • 会话与重试:用requests.Session()维持会话,配合重试策略自动处理请求失败场景,提升爬取成功率
  • 验证检测:通过响应URL判断是否被反爬拦截,提前给出提示
  • 分层定位:先找价格容器再提取具体价格,避免因页面局部结构变动导致定位失败
  • 异常捕获:捕获请求全流程异常,避免程序直接崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:45:19