【问题标题】:How to use Scrapy FormRequest in a loop如何在循环中使用 Scrapy FormRequest
【发布时间】:2021-02-14 19:25:56
【问题描述】:

我正在尝试创建一个蜘蛛,它将列表中的单词一个一个地放入引用的搜索输入中,然后解析结果页面中的文本。

它适用于一个单词,但我不能让它适用于整个列表。我猜我应该(以某种方式)把循环放在蜘蛛里面?

我的代码如下。它是作为其他几个 Stack Overflow 建议的汇编而产生的。问题是爬虫被更新为words 中的最后一个单词,并忽略了列表的其余部分。由于“ReactorNotRestartable”错误,我无法将crawler.start() 放入循环中。

class FirstSpider(scrapy.Spider):
    name = 'ruscorpora'

    def start_requests(self):
            yield scrapy.Request('https://ruscorpora.ru/new/search-main.html', callback=self.form_input)
    
    def form_input(self, response):
            return scrapy.FormRequest.from_response(response, formdata={'req': the_word}, callback=self.parse_freq)
    
    def parse_freq(self, response):
        xpath = "/html/body/div[4]/p[3]/span[3]/text()"
        message = response.xpath(xpath).extract_first()
        
        if message is None:            #in case there isn't a word like that
            result.append(0)
        else:
            result.append(message)

words = ['parrot','patriot','partjbndonfc']
result = []

for the_word in words:
    crawler = CrawlerProcess()
    crawler.crawl(FirstSpider, the_word)

crawler.start()

【问题讨论】:

    标签: python parsing scrapy web-crawler reactor


    【解决方案1】:

    你可以这样

    class FirstSpider(scrapy.Spider):
        name = 'ruscorpora'
    
        def start_requests(self):
            yield scrapy.Request('https://ruscorpora.ru/new/search-main.html', callback=self.form_input)
        
        def form_input(self, response):
        
            words = ['parrot','patriot','partjbndonfc']
            for word in 
                yield scrapy.FormRequest.from_response(response, formdata={'req': word}, callback=self.parse_freq)
        
        def parse_freq(self, response):
            xpath = "/html/body/div[4]/p[3]/span[3]/text()"
            message = response.xpath(xpath).extract_first()
            
            if message is None:            #in case there isn't a word like that
                result.append(0)
            else:
                result.append(message)
    
    result = []
    
    crawler = CrawlerProcess()
    crawler.crawl(FirstSpider)
    
    crawler.start()
    

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2016-10-06
      • 2012-06-29
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多