【问题标题】:Combining spiders in Scrapy在 Scrapy 中组合蜘蛛
【发布时间】:2014-10-16 15:00:51
【问题描述】:

是否可以创建一个从两个基本蜘蛛继承/使用功能的蜘蛛?

我正在尝试抓取各种网站,我注意到在许多情况下该网站提供了站点地图,但这只是指向类别/列表类型的页面,而不是“真实”内容。因此,我不得不改用 CrawlSpider(指向网站根目录),但这非常低效,因为它会爬过所有页面,包括很多垃圾。

我想做的是这样的:

  1. 启动我的 Spider,它是 SitemapSpider 的子类,并将每个响应传递给 parse_items 方法。
  2. 在 parse_items 中测试页面是否包含“真实”内容
  3. 如果是,则处理它,如果不是,则将响应传递给 CrawlSpider(实际上是我的 CrawlSpider 的子类)来处理
  4. CrawlSpider 然后在页面中查找链接,例如 2 级深度和 处理它们

这可能吗?我意识到我可以将 CrawlSpider 中的代码复制并粘贴到我的蜘蛛中,但这似乎是一个糟糕的设计

【问题讨论】:

    标签: scrapy


    【解决方案1】:

    最后我决定只扩展站点地图蜘蛛并从抓取蜘蛛中提取一些代码,因为尝试处理多重继承问题更简单:

    class MySpider(SitemapSpider):
       def __init__(self, **kw):
          super(MySpider, self).__init__(**kw)
          self.link_extractor = LxmlLinkExtractor()
    
       def parse(self, response):
          # perform item extraction etc
          ...
          links = self.link_extractor.extract_links(response)
          for link in links:
            yield Request(link.url, callback=self.parse) 
    

    【讨论】:

    • 您好 toby,我正在尝试做一些类似于您所描述的事情,您能否提供一些关于您如何解决问题的 sn-ps。谢谢
    【解决方案2】:
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import SitemapSpider, CrawlSpider, Rule
    
    class MySpider(SitemapSpider, CrawlSpider):
        name = "myspider"
        rules = ( Rule(LinkExtractor(allow=('', )), callback='parse_item', follow=True), )
        sitemap_rules = [ ('/', 'parse_item'), ]
        sitemap_urls = ['http://www.example.com/sitemap.xml']
        start_urls = ['http://www.example.com']
        allowed_domains = ['example.com']
    
        def parse_item(self, response):
            # Do your stuff here
            ...
            # Return to CrawlSpider that will crawl them
            yield from self.parse(response)
    

    这样,Scrapy 将从站点地图中的 url 开始,然后跟随每个 url 中的所有链接。

    来源:Multiple inheritance in scrapy spiders

    【讨论】:

      【解决方案3】:

      你可以像往常一样继承,唯一需要注意的是基础蜘蛛通常会覆盖基本方法start_requestsparse。需要指出的另一件事是,CrawlSpider 将从通过_parse_response 的每个响应中获取链接。

      【讨论】:

        【解决方案4】:

        设置一个较低的值 do DEPTH_LIMIT 应该是管理 CrawlSpider 将为通过 _parse_response 的每个响应获取链接这一事实的一种方式(在查看原始问题后,它已被提议)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多