2017-11-12 4 views
1

私はサイトにアクセスしようとしていて、サイト内のページにリダイレクトされているリンクがないかどうかチェックしています。利用可能なサイトマップがないので、私はScrapyを使用してサイトをクロールし、各ページのすべてのリンクを取得していますが、見つかったすべてのリンクとそのステータスコードを含むファイルを出力できません。私はコードをテストするために使用しているサイトはquotes.toscrape.comで、私のコードは次のとおりです。Scrapyですべてのhttpリクエストを取得できない

from scrapy.spiders import Spider 
from mytest.items import MytestItem 
from scrapy.http 
import Request 
import re 
class MySpider(Spider): 
    name = "sample" 
    allowed_domains = ["quotes.toscrape.com"] 
    start_urls = ["http://quotes.toscrape.com"] 
    def parse(self, response): 
     links = response.xpath('//a/@href').extract() 
\# We stored already crawled links in this list 
     crawledLinks = [] 
     for link in links: 
\# If it is a proper link and is not checked yet, yield it to the Spider 
     if link not in crawledLinks: 
      link = "http://quotes.toscrape.com" + link 
      crawledLinks.append(link) 
      yield Request(link, self.parse) 

私は降伏した後、次の行を追加しようとしました:

item = MytestItem() 
item['url'] = link 
item['status'] = response.status 
yield item 

しかし、それは私を取得します重複の束とステータス404または301のURLはありません。どのように私はステータスですべてのURLを取得することができます誰も知っていますか?

答えて

1

デフォルトでは、Scrapyは失敗したリクエストを返しませんが、errback on the requestを設定すると、それらをフェッチして関数のいずれかで処理できます。

def parse(self, response): 
    # some code 
    yield Request(link, self.parse, errback=self.parse_error) 

def parse_error(self, failure): 
    # log the response as an error 

パラメータfailureは、HTTPエラー可能性があるため(あなたが応答を取得することができる)、失敗のmore information on the exact reasonが含まれている、だけでなく、(応答がない)ルックアップエラーとそのようにDNSます。

ドキュメントが利用できる場合は、エラーの理由とアクセスResponseを決定するために、障害をどのように使うかの例が含まれています

def errback_httpbin(self, failure): 
    # log all failures 
    self.logger.error(repr(failure)) 

    # in case you want to do something special for some errors, 
    # you may need the failure's type: 

    if failure.check(HttpError): 
     # these exceptions come from HttpError spider middleware 
     # you can get the non-200 response 
     response = failure.value.response 
     self.logger.error('HttpError on %s', response.url) 

    elif failure.check(DNSLookupError): 
     # this is the original request 
     request = failure.request 
     self.logger.error('DNSLookupError on %s', request.url) 

    elif failure.check(TimeoutError, TCPTimedOutError): 
     request = failure.request 
     self.logger.error('TimeoutError on %s', request.url) 
+0

ありがとう、私は404エラーを記録することができませんでしたが、私はそれがurlがrobot.txtファイルだったためだと思います。私はどのようにファイルのURLと応答を得ることができるか知っていますか? Scrapyは実行中にすでに私を表示していますが、-o file -t型を使用してもファイルを作成しません。 – SamuelSV

+0

最も簡単な方法は[feed exporters](https://doc.scrapy.org/en/latest/topics/feed-exports.html)です。 (CSV、JSON、...)書式(ファイルベース)と書式を選択するだけです。 'FEED_FORMAT'と' FEED_URI'オプションは 'settings.py'に追加する必要があります。ファイルベースの出力の場合は、 'FEED_FORMAT =" file:///tmp/export.csv "'のように設定します。 – Aufziehvogel

1

あなたの設定でHTTPERROR_ALLOW_ALLを使用するか、またはすべてのあなたの要求にメタキーhandle_httpstatus_all = Trueを設定する必要があり、詳細については、ドキュメントを参照してください。

関連する問題