使用BeautifulSoup爬取亚马逊产品信息时遇AttributeError问题求助
解决BeautifulSoup获取Amazon产品信息时的AttributeError问题
错误核心原因
AttributeError: 'NoneType' object has no attribute 'text' 本质是soup.find()没有找到指定的<span>标签,返回了None,后续调用.text触发了错误。常见诱因包括:
- Amazon反爬机制拦截请求,返回的不是正常搜索结果页面(比如验证码页)
- 目标标签的class名称已更新,和代码中写的不一致
- 请求头未设置,被识别为非浏览器请求
分步解决方法
1. 先验证请求是否成功
先确认请求拿到的是正常页面,避免做无用功:
response = requests.get(url) print(response.status_code) # 正常应返回200 print(response.text[:500]) # 打印前500字符,判断是否是验证码页面
2. 添加浏览器请求头
模拟浏览器发送请求,绕过基础反爬:
def Bprice2(url): print("Fetching details....") # 可通过https://www.whatismybrowser.com/detect/what-is-my-user-agent/获取自己的User-Agent headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } response = requests.get(url, headers=headers) if response.status_code != 200: print(f"请求失败,状态码:{response.status_code}") return soup = BeautifulSoup(response.content, 'html.parser') # 先判断标签是否存在,再获取文本 name_tag = soup.find('span', {'class': 'a-size-medium a-color-base a-text-normal'}) if name_tag: print(name_tag.text.strip()) else: print("未找到产品名称对应的标签") URL2 = 'https://www.amazon.in/s?k=iphone+11' bestprice2 = Bprice2(URL2)
3. 确认目标标签的正确性
如果添加请求头后仍找不到标签,手动核对页面结构:
- 打开Amazon搜索页面,右键点击产品名称选择「检查」
- 查看对应
<span>标签的class属性,确认是否和代码中的一致(Amazon经常更新页面结构) - 若class已变更,替换成新名称,或者用更灵活的CSS选择器:
# 定位所有产品卡片里的标题标签 name_tags = soup.select('div[data-asin] h2 span') if name_tags: for tag in name_tags: print(tag.text.strip())
4. 增加异常捕获
避免程序因意外情况崩溃:
def Bprice2(url): print("Fetching details....") headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } try: response = requests.get(url, headers=headers) response.raise_for_status() # 触发HTTP错误异常 soup = BeautifulSoup(response.text, 'html.parser') name_tag = soup.find('span', {'class': 'a-size-medium a-color-base a-text-normal'}) print(name_tag.text.strip() if name_tag else "未找到产品名称") except Exception as e: print(f"出错:{str(e)}") URL2 = 'https://www.amazon.in/s?k=iphone+11' bestprice2 = Bprice2(URL2)
内容的提问来源于stack exchange,提问作者Arshdeep Singh Bhatia
相关产品推荐
相关产品推荐

