2017-04-06 8 views
0

私はScrapyを一度も使用していません。 助けてください!Python Scrapy:self.download_delayを使用するには

私は "next_link" で各要求の遅延を作りたい

例:

GET https://example.com/?page=1

遅延30秒

https://example.com/?page=2

遅延30秒をGET

class CVSpider(scrapy.Spider): 
    name = 'cvspider' 
    start_urls = ["login"] 
    custom_settings = { 
     'DOWNLOAD_DELAY': 0, 
     'RANDOMIZE_DOWNLOAD_DELAY': True 
    } 

    def __init__(self, search_url, name=None, **kwargs): 
     self.search_url = search_url 

    def parse(self, response): 
     xsrf = response.css('input[name="_xsrf"] ::attr(value)')\ 
         .extract_first() 
     return scrapy.FormRequest.from_response(
      response, 
      formdata={ 
       'username': USERNAME, 
       'password': PASSWORD, 
       '_xsrf': xsrf 
      }, 
      callback=self.after_login 
     ) 

    def after_login(self, response): 
     self.logger.info('Parse %s', response.url) 
     if "account/login" in response.url: 
      self.logger.error("Login failed!") 
      return 

     return scrapy.Request(self.search_url, callback=self.parse_search_page) 

    def parse_search_page(self, response): 
     cv_hashes = response\ 
      .css('table.output tr[itemscope="itemscope"]::attr(data-hash)')\ 
      .extract() 
     total = len(cv_hashes) 
     start_time = datetime.now() 
     next_link = response.css('a.Controls-Next::attr(href)')\ 
          .extract_first() 
     if total == 0: 
      next_link = None 
     if next_link is not None: 
      self.download_delay = 30 - does not work 
      yield scrapy.Request(
       "https://example.com" + next_link, 
       callback=self.parse_search_page 
      ) 

答えて

0

これを達成するための設定オプションがあります。

DOWNLOAD_DELAY = 30000 # Time in milliseconds (30000 ms = 30 seconds) 

しかし、あなたのコードからcustom_settingsを削除することを忘れないでください:settings.pyファイルでは、このように、DOWNLOAD_DELAYを設定します。


あなたはそのSpiderのカスタム設定でこれを行うにしたい場合は、次のようにコードを変更:

class CVSpider(scrapy.Spider): 
    name = 'cvspider' 
    start_urls = ["login"] 
    custom_settings = { 
     'DOWNLOAD_DELAY': 30000, 
     'RANDOMIZE_DOWNLOAD_DELAY': False 
    } 

    def __init__(self, search_url, name=None, **kwargs): 
    ... 

あなたはその上で、より理解するためにdocumentationを参照することができます。

+0

DOWNLOAD_DELAYは、すべての要求のために設定されますが、私だけのために必要とされています self.download_delay = 30 - 歩留まりscrapy.Request動作しない( –

+0

あなたは、私が設定したい 'スリープ()'ここ –

0

あなたのスパイダーに変数download_delayを設定するだけで、残りの作業は治療が行われます。実際に使用する必要はありません。それだけです

class MySpider(Spider): 
    ... 
    download_delay = 30000 
    ... 

はこれだけのようにそれを設定します。

+0

を使用することができますか? parse_search_page funcの場合のみ遅延 –

関連する問題