【问题标题】:Scrapy CrawlSpider doesn't quitScrapy CrawlSpider 不退出
【发布时间】:2018-08-02 16:40:33
【问题描述】:

我有一个scrapy Crawlspider 的问题:基本上,如果引发CloseSpider 异常,它不会像它应该做的那样退出。下面是代码:

from scrapy.spiders import CrawlSpider, Rule
from scrapy.exceptions import CloseSpider
from scrapy.linkextractors import LinkExtractor
import re

class RecursiveSpider(CrawlSpider):

    name = 'recursive_spider'
    start_urls = ['https://www.webiste.com/']

    rules = (
                Rule(LinkExtractor(), callback='parse_item', follow=True),
                )

    miss = 0
    hits = 0

    def quit(self):
        print("ABOUT TO QUIT")
        raise CloseSpider('limits_exceeded')


    def parse_item(self, response):
        item = dict()
        item['url'] = response.url
        item['body'] = '\n'.join(response.xpath('//text()').extract())
        try:
            match = re.search(r"[A-za-z]{0,1}edical[a-z]{2}", response.body_as_unicode()).group(0)
        except:
            match = 'NOTHING'

        print("\n")
        print("\n")
        print("\n")
        print("****************************************INFO****************************************")
        if "string" in item['url']:    
            print(item['url'])
            print(match)
            print(self.hits)
            self.hits += 10
            if self.hits > 10:
                print("HITS EXCEEDED")
                self.quit()
        else:
            self.miss += 1
            print(self.miss)
            if self.miss > 10:
                print("MISS EXCEEDED")
                self.quit()
        print("\n")
        print("\n")
        print("\n")

问题是,虽然我可以看到它进入了条件,并且我可以看到日志中提出了 Eception,但爬虫仍在继续爬取。 我运行它:

scrapy crawl recursive_spider

【问题讨论】:

    标签: python python-3.x scrapy web-crawler scrapy-spider


    【解决方案1】:

    我猜这是一个scrapy的案例,只是在关闭时花费了太长时间,而不是实际上忽略了异常。引擎在运行完所有计划/发送的请求后才会退出,因此我建议降低 CONCURRENT_REQUESTS/CONCURRENT_REQUESTS_PER_DOMAIN 设置的值以查看是否适合您。

    【讨论】:

    • 是的,这就是问题所在!非常感谢您的帮助。
    【解决方案2】:

    您创建了一个“递归”Spider 运行器,因此它以递归方式运行。去掉“rules”参数,爬完就停止。

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2014-09-13
      相关资源
      最近更新 更多