2017-11-12 3 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 

그러나 그것은 나를 얻는다 중복 및 URL 404 또는 301 상태의 무리. 누구든지 상태와 함께 모든 URL을 얻을 수있는 방법을 알고 있습니까?

답변

1

기본적으로 치료는 실패한 요청을 반환하지 않지만 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

당신은 모든 요청에 ​​메타 키 handle_httpstatus_all = True를 설정에서 HTTPERROR_ALLOW_ALL을 사용하거나 설정해야을, 자세한 정보는 문서를 참조하십시오.