You need to enable JavaScript to run this app. Scrapy爬取BBC美食站点时,如何为每个食谱条目绑定对应cuisine分类字段
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy爬取BBC美食站点时,如何为每个食谱条目绑定对应cuisine分类字段

跨回调传递菜系字段的实现方案

你之前的实现报错的核心原因是Scrapy异步请求的无状态特性:不同回调函数之间的局部变量是完全隔离的,不会自动传递值,只要在某一层生成新请求时没有显式把需要的字段透传,到下一层解析时就找不到对应的变量,自然会抛出报错。

第一步:菜系入口页同步提取菜系标识

修改parse_cuisines方法,不再只提取菜系链接,同时提取每个链接对应的菜系文本值,利用Request自带的meta参数作为跨回调传值的标准渠道,把值向下层解析流程传递。

def parse_cuisines(self, response):
    # 定位所有菜系链接节点,同步提取href和对应的菜系名称
    cuisine_links = response.xpath('//a[contains(@class,"promo__cuisine")]')
    for link in cuisine_links:
        cuisine_href = link.xpath('./@href').get()
        # 提取菜系文本,转小写作为cuisine字段值,比如"Italian"转换为"italian"
        cuisine_name = link.xpath('./text()').get().strip().lower()
        # 通过meta参数把菜系值传给下一层的列表页解析回调
        yield response.follow(
            url=cuisine_href,
            callback=self.parse_main,
            meta={"cuisine": cuisine_name}
        )

第二步:列表页透传字段到下一层请求

修改parse_main方法,不管是跟进食谱详情链接、还是生成分页跳转请求,都要把当前携带的菜系值通过meta透传,不能在跳转环节丢值。

def parse_main(self, response):
    # 从当前请求的meta中取出之前透传的菜系值
    current_cuisine = response.meta["cuisine"]
    recipe_cards = response.xpath('//a[contains(@class,"main_course")]/@href').extract()
    for url in recipe_cards:
        # 给食谱详情页请求带上菜系meta值
        yield response.follow(
            url=url,
            callback=self.parse_card,
            meta={"cuisine": current_cuisine}
        )
    next_page = response.xpath('//div[@class="pagination gel-wrap"]/ul[@class="pagination__list"]/li[@class="pagination__list-item pagination__priority--0"]/a[@class="pagination__link gel-pica-bold"]/@href').get()
    if next_page is not None:
        next_page_url = response.urljoin(next_page)
        # 给分页跳转请求同样带上菜系meta值,避免翻页后值丢失
        yield scrapy.Request(
            url=next_page_url,
            callback=self.parse_main,
            meta={"cuisine": current_cuisine}
        )

第三步:详情页解析时给Item字段赋值

修改parse_card方法,从请求的meta中取出透传的菜系值,赋值给Item中已经定义好的cuisine字段,就可以正常随其他字段导出到CSV。

def parse_card(self, response):
    item = RecipeItem()
    item['name'] = response.xpath('//h1[contains(@class,"title__text")]/text()').extract()
    item['prep_time'] = response.xpath('//div[contains(@class,"recipe-metadata-wrap")]/p[@class="recipe-metadata__prep-time"]/text()').extract_first()
    item['cook_time'] = response.xpath('//p[contains(@class,"cook-time")]/text()').extract_first()
    item['servings'] = response.xpath('//p[contains(@class,"serving")]/text()').extract_first()
    item['ratings_amount'] = response.xpath('//div[contains(@class,"aggregate-rating")]/span[contains(@class,"aggregate-rating__total")]/text()').extract()
    item['ingredients'] = response.css('li.recipe-ingredients__list-item > a::text').extract()
    # 取出透传的菜系值赋值给对应字段
    item['cuisine'] = response.meta["cuisine"]
    return item

注意事项

  • 不要跨回调直接引用上层方法的局部变量:Scrapy是异步调度执行的,上层回调执行完成后对应的局部变量就会被系统回收,下层回调根本无法访问,这是之前尝试赋值时报错的最常见原因
  • 透传meta时不要漏掉手动生成的请求:尤其是分页跳转的请求,很多人只给食谱详情请求加了meta,分页请求没加,导致翻页后同个菜系的所有食谱都丢失了cuisine值
  • 现有Item定义不需要修改:你已经在RecipeItem类中预留了cuisine字段,只要正确赋值就可以正常导出,不需要额外调整Item结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 19:24:01