2011-12-19 17 views
9

Tôi đang sử dụng mẩu tin lưu niệm để thu thập dữ liệu trang web có vẻ như đang thêm các giá trị ngẫu nhiên vào chuỗi truy vấn ở cuối mỗi URL. Điều này đang biến thu thập thông tin thành một loại vòng lặp vô hạn.Làm cách nào để xóa truy vấn khỏi url?

Làm cách nào để tôi bỏ qua phần chuỗi truy vấn của URL?

Trả lời

20

Xem urllib.urlparse

Mã ví dụ:

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

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

đầu ra Ví dụ:

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

Đây có phải là: 'từ urllib.parse import urlparse'? –

+0

@RyanCady yes 'từ urllib.parse import urlparse' làm việc cho tôi. – nipunasudha

6

Cung cấp một số mã để chúng tôi có thể trợ giúp bạn.

Nếu bạn đang sử dụng CrawlSpiderRule với SgmlLinkExtractor, hãy cung cấp chức năng tùy chỉnh cho proccess_value thông số của SgmlLinkExtractor hàm tạo.

Xem tài liệu cho 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

Cả hai câu trả lời đầu tiên và thứ hai dường như để giải quyết vấn đề của tôi. Tôi không chắc chắn làm thế nào tôi có thể đánh dấu cả hai câu trả lời là chính xác –

0

Nếu bạn đang sử dụng BaseSpider, trước khi năng suất một yêu cầu mới, loại bỏ các giá trị tự ngẫu nhiên từ phần truy vấn của URL sử dụng 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ó một chức năng url_query_cleaner trong w3lib.url mô-đun (được sử dụng bởi scrapy chính nó) để làm sạch các url chỉ giữ lại một danh sách các đối số cho phép.