You need to enable JavaScript to run this app. Python BeautifulSoup爬虫报IndexError列表索引越界问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Python BeautifulSoup爬虫报IndexError列表索引越界问题求解

爬虫价格字段索引错位问题解决方案

核心原则:不要全局分别提取各字段再按索引对应,改为先定位单个商品父节点,再在节点内部提取对应字段,从根源避免索引错位。

  • 第一步:定位商品列表中每个独立商品的外层父容器,提取全部16个父节点,确保每个父节点对应一个完整商品
  • 第二步:在单个父节点内部查询价格字段,使用CSS属性包含匹配规则,跳过额外class的干扰:BeautifulSoup的select/select_one方法支持[class*="属性片段"]语法,只要class属性包含price--withoutTax即可命中,无需匹配全部class值
  • 第三步:对查询到的价格标签做非空判断,存在则提取文本,不存在则填充默认占位值,避免空指针异常

参考实现代码:

# 替换为目标站点实际的商品父节点选择器
product_items = soup.select('.product-item')
result = []
for item in product_items:
    # 替换为实际标题选择器,在单个商品节点内提取标题
    title = item.select_one('.product-title').get_text(strip=True)
    # 模糊匹配价格class,忽略额外的price-per--case属性
    price_tag = item.select_one('[class*="price--withoutTax"]')
    price = price_tag.get_text(strip=True) if price_tag else None
    # 其余字段同理在当前item内提取
    result.append({
        "title": title,
        "price": price
    })

可选精确匹配方案:如果需要严格匹配两种已知的价格class场景,可以直接写多选择器同时命中:
price_tag = item.select_one('.price.price--withoutTax, .price.price--withoutTax.price-per--case')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 06:45:03