【问题标题】:Scrapy crawlspider rulesScrapy爬虫规则
【发布时间】:2019-07-11 12:28:23
【问题描述】:

基本的蜘蛛工作。 然后我将它转换为 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

【问题讨论】:

  • 您好,欢迎您。 doesn't work anymore 永远不会自我解释。你得到什么错误?或者结果是什么?它与您的预期有何不同?您应该编辑您的问题并添加更多信息,以便更好地获得快速和相关的答案。此外,请避免在一个问题中提出多个问题:使用单独的帖子。在 SO 上玩得开心。

标签: python scrapy rules


【解决方案1】:
  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") 

【讨论】:

  • 您好 Wim,感谢您的重播!您的第一个解决方案有效!它现在给出输出。
  • 我在为你挣扎 3 点。它不起作用。你能提供更多细节吗?我还想只提取产品 response.xpath("//div[@data-testid='bonus-lane--AH']") 或排除使用类似 xpath 提到的产品。我怎样才能做到这一点?感谢您的帮助!
  • 这个想法是确定xpath中是否有值,如果有,则删除该项目。我的解决方案确实不起作用,因为该部分是动态加载的。这里最简单的可能是检查数据的来源,并尝试根据您可以丢弃该项目的内容来确定。要限制 LinkExtractor 中的结果,您可以添加:restrict_xpaths='//div[@data-testid="bonus-lane--AH"]'
【解决方案2】:

感谢您的反应。我没有收到任何错误,只是一个空文件。 希望您可以对代码提供一些反馈?

谢谢你的手! 抢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多