2011-12-19 15 views
9

Sto utilizzando scrapy per eseguire la ricerca per indicizzazione di un sito che sembra aggiungere valori casuali alla stringa di query alla fine di ciascun URL. Questo sta trasformando la scansione in una sorta di ciclo infinito.Come rimuovo una query da un url?

Come faccio a rendere scrapy trascurabile la parte stringa di query degli URL?

risposta

20

Vedi urllib.urlparse

Codice di esempio:

from urlparse import urlparse 
o = urlparse('http://url.something.com/bla.html?querystring=stuff') 

url_without_query_string = o.scheme + "://" + o.netloc + o.path 

uscita Esempio:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from urlparse import urlparse 
>>> o = urlparse('http://url.something.com/bla.html?querystring=stuff') 
>>> url_without_query_string = o.scheme + "://" + o.netloc + o.path 
>>> print url_without_query_string 
http://url.something.com/bla.html 
>>> 
+1

In questo caso: 'da urllib.parse import urlparse'? –

+0

@RyanCady yes 'da urllib.parse import urlparse' ha funzionato per me. – nipunasudha

6

Fornire un codice, in modo che possiamo aiutarti.

Se si utilizza CrawlSpider e Rule 's con SgmlLinkExtractor, forniscono funzione personalizzata per proccess_value parametro del SgmlLinkExtractor costruttore.

vedere la documentazione per BaseSgmlLinkExtractor

def delete_random_garbage_from_url(url): 
    cleaned_url = ... # process url somehow 
    return cleaned_url 

Rule(
    SgmlLinkExtractor(
     # ... your allow, deny parameters, etc 
     process_value=delete_random_garbage_from_url, 
    ) 
) 
+0

Sia il primo che il secondo tasto di risposta sembrano risolvere il mio problema. Non sono sicuro di come sia possibile correggere entrambe le risposte. –

0

Se si utilizza BaseSpider, prima di cedere una nuova richiesta, rimuovere valori casuali manualmente dalla parte query dell'URL con urlparse:

def parse(self, response): 
    hxs = HtmlXPathSelector(response) 
    item_urls = hxs.select(".//a[@class='...']/@href").extract() 
    for item_url in item_urls: 
     # remove the bad part of the query part of the URL here 
     item_url = urlparse.urljoin(response.url, item_url) 
     self.log('Found item URL: %s' % item_url) 
     yield Request(item_url, callback = self.parse_item) 
10

C'è una funzione url_query_cleaner nel modulo w3lib.url (usato da Scrapy stesso) per pulire URL lasciando solo un elenco di argomenti consentiti.

Problemi correlati