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

如何为Scrapy爬虫获取商品多级分类及产品序列号?

解决方案

1. 完整分类层级爬取

实现思路

先遍历完整分类链路(主分类→二级分类→三级子分类),再进入子分类页面爬取对应商品,而非直接从主分类页抓取商品,确保每个商品都能关联到完整的三级分类信息。

代码调整示例

import scrapy
from your_project.items import StoreItem

class StoreSpider(scrapy.Spider):
    name = 'online_store'
    allowed_domains = ['target-store.com']
    start_urls = ['https://target-store.com/categories']

    def parse(self, response):
        # 解析主分类下的二级分类链接
        main_cat_name = response.css('div.main-cat h2::text').get().strip()
        sub_cat_links = response.css('div.main-cat a.sub-cat-link::attr(href)').getall()
        for link in sub_cat_links:
            yield response.follow(link, callback=self.parse_sub_cat, meta={'main_category': main_cat_name})

    def parse_sub_cat(self, response):
        # 解析二级分类下的三级子分类链接
        sub_cat_name = response.css('div.sub-cat h3::text').get().strip()
        child_cat_links = response.css('div.sub-cat a.child-cat-link::attr(href)').getall()
        for link in child_cat_links:
            meta = response.meta.copy()
            meta['category'] = sub_cat_name
            yield response.follow(link, callback=self.parse_products, meta=meta)

    def parse_products(self, response):
        # 获取三级子分类名称
        child_cat_name = response.css('div.child-cat h4::text').get().strip()
        # 遍历当前子分类下的商品链接
        product_links = response.css('div.product-card a.product-url::attr(href)').getall()
        for link in product_links:
            meta = response.meta.copy()
            meta['sub_category'] = child_cat_name
            yield response.follow(link, callback=self.parse_product_detail, meta=meta)

        # 处理分页逻辑
        next_page = response.css('a.next-page-btn::attr(href)').get()
        if next_page:
            yield response.follow(next_page, callback=self.parse_products, meta=response.meta)

2. 产品序列号爬取

实现思路

进入商品详情页后,定位到展示产品序列号的DOM元素(通常在商品规格栏、详情底部或参数表中),提取对应文本内容。

代码调整示例

在爬虫类中添加详情页解析函数:

def parse_product_detail(self, response):
    item = StoreItem()
    # 从meta中提取完整分类层级
    item['main_category'] = response.meta.get('main_category')
    item['category'] = response.meta.get('category')
    item['sub_category'] = response.meta.get('sub_category')
    # 提取产品序列号(需根据目标网站实际DOM结构调整选择器)
    item['product_serial'] = response.css('div.product-spec span.serial-code::text').get().strip()
    # 可补充其他商品字段提取
    item['product_name'] = response.css('h1.product-title::text').get().strip()
    item['price'] = response.css('span.price-tag::text').get().strip()
    
    yield item

关键注意事项

  • 必须替换代码中的CSS选择器为目标网站实际的DOM结构(参考你提供的截图调整)
  • 若网站存在反爬机制,需在settings.py中配置USER_AGENT、设置DOWNLOAD_DELAY或使用代理
  • 确保项目的items.py中已定义对应字段:main_category、category、sub_category、product_serial等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:28:24