2017-12-20 5 views
0

Kann mir jemand helfen, die Erfassung des Antwortstatuscodes für jede Crawling-Anfrage zu verstehen, die meine Scrapy Spider gemacht hat. Ich war in der Lage, die Ausgabe für Resp-Code 200 zu bekommen, aber wenn die Website 404 Fehler hat, schreibt es keine Ausgabe einschließlich 301 und 302 auch.Crawlen von Webseiten und Erfassen verschiedener Antwortstatuscodes mithilfe von Python Scrapy

Hier ist der Code, den ich für eine andere Website implementiert habe, und einen Domänennamen mit meinem Namen als Referenz hinzugefügt.

import scrapy 
import requests 
from scrapy.linkextractors import LinkExtractor 
from scrapy.selector import Selector 
from scrapy.spiders import Rule, CrawlSpider 



class TestSpider(CrawlSpider): 
    name = 'TestSpider' 
    handle_httpstatus_list = [404] 
    resp_log_file = 'C:\\resp' 
    ok_log_file = 'C:\\alright' 
    bad_log_file = 'C:\\badresp' 
    redirect_log_file = 'C:\\redirect' 

    allowed_domains = ['santhosh.com'] 
    start_urls = ['santhosh.com/'] 

    # This spider has one rule: extract all (unique and canonicalized) links, follow them and parse them using the parse_items method 
    rules = [ 
     Rule(
      LinkExtractor(
       canonicalize=True, 
       unique=True 
      ), 
      follow=True, 
      callback="parse_item" 
     ) 
    ] 

    def parse_item(self, response): 
     # The list of items that are found on the particular page 
     items = [] 
     res = Selector(response) 
     self.append(self.resp_log_file, str(response)) 
     # Only extract canonicalized and unique links (with respect to the current page) 
     links = LinkExtractor(canonicalize=True, unique=True).extract_links(response) 
     try: 
      if response.status == 404: 
       ## 404 tracciate anche separatamente 
       self.append(self.bad_log_file, response.url) 
      elif response.status == 200: 
       ## printa su ok_log_file 
       self.append(self.ok_log_file, response.url) 
      elif response.status == 302: 
       ## printa su ok_log_file 
       self.append(self.redirect_log_file, response.url) 
      else: 
       self.append(self.bad_log_file, response.url) 
     except Exception, e: 
      pass 

     return None 


    def append(self, file, string): 
     print " Writing content to File " 
     file = open(file, 'a') 
     file.write(string+"\n") 
     file.close() 

Ich habe Fragen Antwortcode Erfassung im Zusammenhang gesehen, aber sie waren nicht gerade ähnlich wie meine Anfragen und damit diese neue Stelle geschaffen. Wenn bereits eine Frage verfügbar ist, bitte ich Sie, dies zu ignorieren und mich dort weiterzuleiten. Danke im Voraus!

+0

wikipedia: [Liste der HTTP-Statuscodes] (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) – furas

+0

'200' = "Seite ohne Probleme bekommen",' 404' = „Seite nicht gefunden ",' 30x' = "Weiterleitung wegen XXX". Wenn Scrapy die Seite nicht lesen kann (dh "404"), ruft sie den Parser nicht auf. – furas

+0

Verwenden Sie nicht 'exception Exception, e: pass', weil Sie möglicherweise einen unerwarteten Fehler haben und Sie es nicht wissen. Atleast display es außer Ausnahme, e: print ("ERROR:", e) ' – furas

Antwort

0

Ich habe versucht, Code und ich sehe es 404 und 301 zu parse() sendet, nicht zu parse_item() aber ich habe keine Seite mit defekten Links, damit es nicht LinkExtractor

läuft I Portal httpbin.org verwendeten Seiten zu erzeugen, mit anderer Status

Vielleicht, wenn ich Seite mit gebrochenen URLs habe, dann könnte LinkExtractor laufen und ich könnte andere Ergebnisse bekommen.

#!/usr/bin/env python3 

import scrapy 
from scrapy.linkextractors import LinkExtractor 
from scrapy.selector import Selector 
from scrapy.spiders import Rule, CrawlSpider 
#from scrapy.commands.view import open_in_browser 

class MySpider(CrawlSpider): 

    name = 'MySpider' 

    handle_httpstatus_list = [404, 301, 302, 303] 

    all_responses_log = './responses_all.log' 
    ok_responses_log = './responses_ok.log' 
    bad_responses_log = './responses_bad.log' 
    redirects_responses_log = './responses_redirect.log' 

    start_urls = [ 
     'http://httpbin.org/status/301', 
     'http://httpbin.org/status/302', 
     'http://httpbin.org/status/303', 

     'http://httpbin.org/status/404', 
     'http://httpbin.org/status/200', 
    ] 

    # This spider has one rule: extract all (unique and canonicalized) links, follow them and parse them using the parse_items method 
    rules = [ 
     Rule(
      LinkExtractor(
       canonicalize=True, 
       unique=True 
      ), 
      follow=True, 
      callback="parse_item" 
     ) 
    ] 

    def parse(self, response): 
     print('parse url:', response.url) 

     self.test_status('parse()', response) 

    def parse_item(self, response): 
     print('parse item url:', response.url) 

     self.test_status('parse_item()', response) 

     # The list of items that are found on the particular page 
     items = [] 
     res = Selector(response) 
     self.append(self.resp_log_file, str(response)) 
     # Only extract canonicalized and unique links (with respect to the current page) 
     links = LinkExtractor(canonicalize=True, unique=True).extract_links(response) 

    def test_status(self, text, response): 
     try: 
      if response.status == 404: 
       log = self.bad_responses_log 
      elif response.status == 200: 
       log = self.ok_responses_log 
      #elif 299 < response.status < 400: 
      elif response.status in (301, 302, 303, 307): 
       log = self.redirects_responses_log 
      else: 
       log = self.redirects_responses_log 

      message = "{} | {} | {}\n".format(response.status, text, response.url) 
      self.append(log, message) 
     except Exception as e: 
      print('Error:', e) 

    def append(self, filename, string): 
     print('Writing log:', filename) 
     with open(filename, 'a') as f: 
      f.write(string) 


# --- it runs without project and saves in `output.csv` --- 

from scrapy.crawler import CrawlerProcess 

c = CrawlerProcess({ 
    'USER_AGENT': 'Mozilla/5.0', 
}) 
c.crawl(MySpider) 
c.start() 
+0

Vielen Dank für Ihre Antwort @furas! Ich habe den Code ausprobiert, und ich konnte sehen, dass es nur den endgültigen Statuscode unter den Codes erfasst, die behandelt wurden. Ich habe versucht, 3XX Codes zu entfernen und es erfasst nur 200 Status in der jeweiligen Datei. Ich würde Sie bitten, mir zu helfen, wenn wir den spider.Spider oder den CrawlerSpider verwenden können und den gleichen Ansatz mit zusätzlichen Ratschlägen für Unterseiten (Links) verwenden. Ich habe verwendet (http://httpbin.org), die Links in seiner Seitenquelle hat. – Msk

+0

Gibt es eine Möglichkeit, die Datei, die Domänen enthält, zu verarbeiten, indem Sie diese als ein Argument an den Crawler übergeben, der CrawlSpider verwendet, um ihre Unterseiten ebenfalls mit LinkExtractor zu verarbeiten? – Msk

Verwandte Themen