【问题标题】:How to break out of crawl if certain condition encountered in Scrapy如果在 Scrapy 中遇到某些情况,如何摆脱爬网
【发布时间】:2018-11-13 14:51:55
【问题描述】:

出于我正在开发的应用程序的目的,我需要 scrapy 打破爬网并从特定的任意 URL 重新开始爬网。

如果满足特定条件,scrapy 的预期行为是返回到可以在参数中提供的特定 URL。

我正在使用 CrawlSpider,但不知道如何实现:

class MyCrawlSpider(CrawlSpider):
    name = 'mycrawlspider'
    initial_url = ""

    def __init__(self, initial_url, *args, **kwargs):
        self.initial_url = initial_url
        domain = "mydomain.com"
        self.start_urls = [initial_url]
        self.allowed_domains = [domain]
        self.rules = (
            Rule(LinkExtractor(allow=[r"^http[s]?://(www.)?" + domain + "/.*"]), callback='parse_item', follow=True),
        )

        super(MyCrawlSpider, self)._compile_rules()


    def parse_item(self, response):
        if(some_condition is True):
            # force scrapy to go back to home page and recrawl
            print("Should break out")

        else:
           print("Just carry on")

我试着放置

return scrapy.Request(self.initial_url, callback=self.parse_item)

someCondition is True 的分支中但没有成功。非常感谢一些帮助,一直在努力解决这个问题几个小时。

【问题讨论】:

  • 请澄清,你想重启蜘蛛吗?
  • 抱歉我不够清楚,我希望它转到特定的 URL(可以通过参数提供)。然后,我会将其设置为我认为合适的条件

标签: python scrapy web-crawler


【解决方案1】:

您可以进行适当处理的自定义异常,就像这样...

请随意使用适当的 CrawlSpider 语法进行编辑

class RestartException(Exception):
    pass

class MyCrawlSpider(CrawlSpider):
    name = 'mycrawlspider'
    initial_url = ""

    def __init__(self, initial_url, *args, **kwargs):
        self.initial_url = initial_url
        domain = "mydomain.com"
        self.start_urls = [initial_url]
        self.allowed_domains = [domain]
        self.rules = (
            Rule(LinkExtractor(allow=[r"^http[s]?://(www.)?" + domain + "/.*"]), callback='parse_item', follow=True),
        )

        super(MyCrawlSpider, self)._compile_rules()


    def parse_item(self, response):
        if(some_condition is True):

            print("Should break out")
            raise RestartException("We're restarting now")

        else:
           print("Just carry on")

siteName = "http://whatever.com"
crawler = MyCrawlSpider(siteName)           
while True:
    try:
        #idk how you start this thing, but do that

        crawler.run()
        break
    except RestartException as err:
        print(err.args)
        crawler.something = err.args
        continue

print("I'm done!")

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2011-03-16
    • 2017-01-25
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多