2017-11-23 37 views
0

私はページのリストをクロールしています。各ページには、解析する必要があるURLのリストがあります。私はこれらの最初のページをループしていますが、いつクロールをやめなければならないのかは分かりません。ないScrapy:クロールの確認と停止の方法

http://www.cmjornal.pt/opiniao/colunistas/acacio-pereira/MoreContent?firstContent=183

ではなく、この1すでに空であるため:たとえば、この1は、解析されることはまだある

http://www.cmjornal.pt/opiniao/colunistas/acacio-pereira/MoreContent?firstContent=200

だから私の質問は:私は、クローラを停止することができますか条件をURL解析から見つけましたか?私はCloseSpider()を使用しようとしましたが、他のURLが解析される前にスパイダーを完全に閉じるため、動作しません。

class CmSpider(scrapy.Spider): 
    name = "historical" 
    start_urls = ['http://www.cmjornal.pt/opiniao/colunistas/acacio-pereira/MoreContent?firstContent='] 
    hostname = 'http://www.cmjornal.pt' 


    def parse(self, response): 
     for i in range(180,200,3): 
      url = response.url + str(i) 
      yield scrapy.Request(url,callback=self.parse_page,priority = 1) 

    def parse_page(self,response): 
     if len(response.xpath('/html/body//*')) <= 2: 
      raise CloseSpider('bandwidth_exceeded') 
     else: 
      pass 


     articles_url = response.xpath('//*[@class="lead"]/../h3/a/@href').extract() 
     for url in articles_url: 
      url = self.hostname+url 
      item = CmItem() 
      item['hostname'] = self.hostname 
      request = scrapy.Request(url,callback=self.parse_article) 
      request.meta['item'] = item 
      yield request 

    def parse_article(self,response): 
     item = response.meta['item'] 

     (...) 

注:

私はCloseSpider()で使用しているコードを示し、コンテンツが終了するとき、私が知っているこの特定のケースのために、私は、他の多くの例のためにこれを実行する必要があり、そのIドンそのような限界を知っていない。

答えて

1

代わりに、このような何かをクモを閉じる多くの要求をもたらす停止する必要があります:

# -*- coding: utf-8 -*- 
import scrapy 
from w3lib.url import add_or_replace_parameter 
from w3lib.url import url_query_parameter 


class HistorialSpider(scrapy.Spider): 
    name = 'historial' 
    allowed_domains = ['cmjornal.pt'] 

    def start_requests(self): 
     base_url = 'http://www.cmjornal.pt/opiniao/colunistas/acacio-pereira/MoreContent' 
     new_url = add_or_replace_parameter(base_url, 'firstContent', 180) 
     yield scrapy.Request(new_url, callback=self.parse_page) 

    def parse_page(self, response): 
     if len(response.xpath('/html/body//*')) <= 2: 
      return 

     next_page = int(url_query_parameter(response.url, 'firstContent')) + 1 
     yield scrapy.Request(add_or_replace_parameter(response.url, 'firstContent', next_page), 
          callback=self.parse_page) 


     articles_url = response.xpath('//*[@class="lead"]/../h3/a/@href').extract() 
     for url in articles_url: 
      yield response.follow(url, callback=self.parse_article) 

    def parse_article(self, response): 
     pass 
+0

[OK]を、ありがとう!それはまさに私が探していたものです。 – Miguel

関連する問題