【问题标题】:how to call one spider from another spider on scrapy如何在scrapy上从另一只蜘蛛中调用一只蜘蛛
【发布时间】:2020-11-19 01:20:21
【问题描述】:

我有两只蜘蛛,我想用抓取的信息给另一只蜘蛛打电话,这些信息不是我可以跟踪的链接。有没有办法从另一个蜘蛛那里调用蜘蛛?

为了更好地说明问题:“一”页面的url是/one/{item_name}的形式,其中{item_name}是我可以从页面/other/得到的信息

...
<li class="item">item1</li>
<li class="item">someItem</li>
<li class="item">anotherItem</li>
...

然后我有爬取/one/{item_name}的蜘蛛OneSpider,以及爬取/other/并检索项目名称的OtherSpider,如下所示:

class OneSpider(Spider):
  name = 'one'

  def __init__(self, item_name, *args, **kargs):
    super(OneSpider, self).__init__(*args, **kargs)
    self.start_urls = [ f'/one/{item_name}' ]
  
  def parse(self, response):
    ...

class OtherSpider(Spider):
  name = 'other'
  start_urls = [ '/other/' ]

  def parse(self, response):
    itemNames = response.css('li.item::text').getall()
    # TODO:
    # for each item name
    # scrape /one/{item_name}
    # with the OneSpider

我已经检查了这两个问题:How to call particular Scrapy spiders from another Python scriptscrapy python call spider from spider,以及其他几个问题,主要解决方案是在类中创建另一个方法并将其作为回调传递给新请求,但我不这么认为当这些新请求具有自定义 url 时适用。

【问题讨论】:

    标签: scrapy


    【解决方案1】:

    Scrapy 不可能从另一个蜘蛛调用蜘蛛。 related issue in scrapy github repo

    但是,您可以将 2 个蜘蛛的逻辑合并到单个蜘蛛类中:

    import scrapy
    
    class OtherSpider(scrapy.Spider):
      name = 'other'
      start_urls = [ '/other/' ]
    
      def parse(self, response):
        itemNames = response.css('li.item::text').getall()
        for item_name in itemNames:
          yield scrapy.Request(
            url = f'/one/{item_name}',
            callback = self.parse_item
            )
    
      def parse_item(self, response):
          # parse method from Your OneSpider class
    

    【讨论】:

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