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

使用BeautifulSoup爬取商品信息报错,求代码修复及DataFrame输出

代码修复方案

问题分析

原代码存在几个核心问题:

  • headers未定义,请求易被网站反爬机制拦截
  • 仅用find()获取单个商品,无法抓取页面全部商品数据
  • 未处理元素查找失败的情况(元素不存在时find()返回None,直接调用.text会触发AttributeError)
  • 缺少请求异常处理,单个页面请求失败会导致整个程序终止

修复后的代码

import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
import pandas as pd

# 定义请求头,模拟浏览器访问
headers = {
    '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'
}

key = ['for-babies','beauty','hair','skin','body','gift-packs']
data_main = []

for x in tqdm(key):
    try:
        r = requests.get(f'https://mamaearth.in/product-category/{x}', headers=headers)
        r.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(r.content, 'lxml')
        
        # 获取分类名称,处理元素不存在的情况
        category_elem = soup.find('a', class_='active')
        category = category_elem.text.strip() if category_elem else '未知分类'
        
        # 获取子分类名称,兼容页面结构差异
        sub_category_elem = soup.find('a', class_='SubText-sc-8mwtwz-0') or soup.find('div', class_='sub-category')
        sub_category = sub_category_elem.text.strip() if sub_category_elem else '未知子分类'
        
        # 遍历页面所有商品
        product_items = soup.find_all('div', class_='product-item')
        for item in product_items:
            pro_name_elem = item.find('div', class_='title')
            pro_name = pro_name_elem.text.strip() if pro_name_elem else '未知商品名'
            
            data_main.append({
                'Category': category,
                'Sub_category': sub_category,
                'Pro_Name': pro_name,
            })
    except Exception as e:
        print(f"处理分类{x}时出错: {str(e)}")
        continue

df = pd.DataFrame(data_main)
print(df)

修复说明

  • 补充完整请求头,避免被网站识别为爬虫拦截
  • 改用find_all()抓取页面全部商品,保证数据完整性
  • 对每个元素查找结果做判空处理,避免触发属性错误
  • 加入异常捕获机制,单个页面出错不影响整体程序运行
  • 调整子分类选择器,兼容不同页面的结构差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:36:16