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

Python爬虫问题:PetBarn商品及变体数据提取与CSV导出异常修复

解决PetBarn干狗粮爬虫CSV数据匹配问题

问题根源

你遇到的商品名称重复、规格价格错位问题,核心是未正确处理商品主信息与多SKU(规格/价格)的嵌套关系——一个商品对应多个规格SKU,若循环时未将商品名与每个SKU绑定,就会出现数据对应错误或重复。

修正后的代码

以下代码针对嵌套数据结构做了专门处理,确保商品名与对应规格、价格一一匹配:

import requests
from bs4 import BeautifulSoup
import json
import csv
import re

# 请求页面
url = "https://www.petbarn.com.au/dogs/dog-food/dry-dog-food"
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"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

# 定位存储商品数据的script标签
script_tag = soup.find('script', text=re.compile(r'window\.__INITIAL_STATE__'))
if not script_tag:
    print("未找到目标数据脚本")
    exit()

# 提取并解析JSON内容
json_raw = re.search(r'window\.__INITIAL_STATE__ = ({.*?});', script_tag.string).group(1)
data = json.loads(json_raw)

# 定位商品列表(需根据实际JSON结构调整路径,此处为示例路径)
product_list = data.get('products', {}).get('items', [])
if not product_list:
    print("未提取到商品数据")
    exit()

# 写入CSV文件
with open('dry_dog_food.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=['商品名称', '规格', '价格(澳元)'])
    writer.writeheader()

    # 遍历每个商品,再遍历其下所有规格SKU
    for product in product_list:
        name = product.get('name', '未知名称')
        # 获取当前商品的所有规格SKU
        skus = product.get('skus', [])
        for sku in skus:
            # 提取规格和价格字段
            size = sku.get('attributes', {}).get('size', '未知规格')
            current_price = sku.get('price', {}).get('current', '未知价格')
            # 确保每个规格都绑定对应的商品名称
            writer.writerow({
                '商品名称': name,
                '规格': size,
                '价格(澳元)': current_price
            })

print("CSV文件导出成功")

关键注意事项

  1. JSON路径校验:实际爬取时需打印data结构,确认product_list和skus的准确路径(比如部分网站可能将商品存在catalog或results节点下)
  2. 空值容错:用dict.get()方法加默认值,避免因部分商品字段缺失导致程序崩溃
  3. 请求头伪装:添加User-Agent模拟浏览器请求,防止被网站拦截

内容的提问来源于stack exchange,提问作者X-something

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:40:41