2012-10-25 12 views
7

Ho bisogno di impostare l'URL di riferimento, prima di raschiare un sito, il sito utilizza l'autenticazione basata su url, quindi non mi consente di accedere se il referente non è valido.scrapy come impostare l'URL di riferimento

Qualcuno potrebbe dire come farlo in Scrapy?

risposta

11

Se si desidera cambiare il referer nella richiesta del ragno, è possibile modificare DEFAULT_REQUEST_HEADERS nel file settings.py

Esempio:

DEFAULT_REQUEST_HEADERS = { 'Referer': 'http://www.google.com'
}

3

Basta impostare url Referer nella richiesta intestazioni

class scrapy.http.Request(url[, method='GET', body, headers, ...

headers (dict) – the headers of this request. The dict values can be strings (for single valued headers) or lists (for multi-valued headers).

Esempio:

return Request(url=your_url, headers={'Referer':'http://your_referer_url'})

6

Si dovrebbe fare esattamente come @warwaruk indicato, sotto è il mio esempio elaborazione di un ragno crawl:

from scrapy.contrib.spiders import CrawlSpider 
from scrapy.http import Request 

class MySpider(CrawlSpider): 
    name = "myspider" 
    allowed_domains = ["example.com"] 
    start_urls = [ 
     'http://example.com/foo' 
     'http://example.com/bar' 
     'http://example.com/baz' 
     ] 
    rules = [(...)] 

    def start_requests(self): 
    requests = [] 
    for item in start_urls: 
     requests.append(Request(url=item, headers={'Referer':'http://www.example.com/'})) 
    return requests  

    def parse_me(self, response): 
    (...) 

Questo dovrebbe generare seguenti registri nel tuo terminale:

(...) 
[myspider] DEBUG: Crawled (200) <GET http://example.com/foo> (referer: http://www.example.com/) 
(...) 
[myspider] DEBUG: Crawled (200) <GET http://example.com/bar> (referer: http://www.example.com/) 
(...) 
[myspider] DEBUG: Crawled (200) <GET http://example.com/baz> (referer: http://www.example.com/) 
(...) 

Funzionerà allo stesso modo con BaseSpider. Alla fine il metodo start_requests è il metodo BaseSpider, da cui eredita CrawlSpider.

Documentation spiega più opzioni da impostare in Richiesta a parte le intestazioni, come ad esempio: biscotti, funzione di callback, priorità della richiesta, ecc

Problemi correlati