首页 > 解决方案 > Scrapy爬虫规则

问题描述

基本的蜘蛛工作。然后我将它转换为 CrawlSpider 和规则,不幸的是现在蜘蛛不再工作了。

基本蜘蛛在产品详细信息页面上进行测试: https ://www.ah.nl/producten/product/wi395939/ah-kleintje-boerenkool 然后它获取指定的项目。

我的兴趣是使用 CrawlSpider 浏览所有奖励文章https://www.ah.nl/bonus 进入产品详细信息页面并获取指定信息。

  1. 如何修复我的代码,以便蜘蛛再次工作?

  2. 有人可以解释我在规则上做错了什么吗

  3. 我还想排除 response.xpath("//div[contains(@class,'product-sidebar__products')]") 如果这个“anderen kochten ook”(英文:“other customers both these products”)存在在产品详细信息页面 https://www.ah.nl/producten/product/wi160917/ah-verse-pesto-groen这里存在 https://www.ah.nl/producten/product/wi220252/swiffer- vloerreiniger-navul-stofdoekjes这里不存在

我尝试了很多事情,但无法理解规则

class ahSpider(CrawlSpider):

    name = 'ah'
    allowed_domains = ['ah.nl']  # geen url neer zetten alleen domain name
    start_urls = ['https://www.ah.nl']

    # "anderen kochten ook" "in English: “other customers both these products"
    # response.xpath("//div[contains(@class,'product-sidebar__products')]")

    rules = [
            Rule(LinkExtractor(allow=('/bonus'), deny=('/allerhandebox/', '/allerhande/', '/winkels/', '/acties/', '/klantenservice/', '/zakelijk/', '/bezorgbundel/', '/vakslager/')), follow=True),
        Rule(LinkExtractor(allow=('/producten/product/[0-9]+/[0-9]+'),), callback='parse_items'),
    ]

    #def parse(self, response):
    def parse_items(self, response):
        items = AhItem()

        product_name = response.xpath("//span[contains(@class, 'line-clamp--active')]//text()").extract_first()

        items['product_name']           = product_name
        yield items

标签: pythonscrapyrules

解决方案


  1. 主要问题似乎来自表达式'[0-9]+/[0-9]+'。页面上的链接具有“ https://www.ah.nl/producten/product/wi460830/edet-ultra-soft-tp-magnolia-4-laags ”、“ https:// /www.ah.nl/producten/product/wi210145/heineken-premium-pilsener '。如果您将表达式更改为allow=('/producten/product/')这些产品详细信息链接,则不再过滤掉。
  2. 在 1 下解释
  3. 您可以在 parse_items-method 下包含以下内容:
from scrapy.exceptions import DropItem
others = response.xpath('//div[contains(@class,"product-sidebar__products")]')
if others:
  raise DropItem("'others also bought' present on the product_detail page") 

推荐阅读