2015-12-22 33 views
0

我有以下url開頭:http://somedomain.mytestsite.com/?offset=0。我想通過增加offset參數來循環這個url,比如說每次100。每次我收到響應時,我都需要檢查一些條件以決定是否應該運行下一次迭代。例如:遍歷Scrapy中的url params模板

class SomeSpider(BaseSpider): 
name = 'somespider' 

offset = 0 
items = list() 

def start_requests(self): 
    return [scrapy.Request("http://somedomain.mytestsite.com/?offset="+str(self.offset), callback=self.request_iterator)] 

def request_iterator(self, response): 
    body = response.body 
    #let's say we get json as response data 
    data = json.loads(body) 
    #check if page still have data to process 
    if data["matches"]: 
     self.items.extend(data["matches"]) 
     self.offset += 100 
     return self.start_requests() 
    else: 
     #process collected data in items list 
     return self.do_something_with_items() 

這有效,但我不禁感覺這個代碼有什麼問題。也許我應該使用一些scrapy的rules

回答

1

下面的東西可以改善:

1)不保留的項目,如蜘蛛的屬性,你會消耗的內存量極有更大的投入,使用Python發電機代替。當您使用生成器時,您可以毫不費力地從一個蜘蛛回調中產生項目和請求。

2)start_requests在蜘蛛用於調試,似乎有一點需要覆蓋它們在你的代碼,如果重命名你的方法來解析(默認方法名回調start_requests執行)的代碼將更具可讀性

# we should process at least one item otherwise data["matches"] will be empty. 
start_urls = ["http://somedomain.mytestsite.com/?offset="+1] 

def parse(self, response): 
    body = response.body 
    #let's say we get json as response data 
    data = json.loads(body) 
    #check if page still have data to process 
    if data["matches"]: 
     for x in data["matches"]: 
      yield self.process_your_item(x) 
     self.offset += 100 
     yield self.next_request() 
    else: 
     #process collected data in items list 
     for x self.do_something_with_items(): 
      yield x 

def next_request(self): 
    return scrapy.Request("http://somedomain.mytestsite.com/?offset="+str(self.offset)) 

甚至可能更好版本的回調將是:

def parse(self, response): 
    body = response.body 
    #let's say we get json as response data 
    data = json.loads(body) 
    #check if page still have data to process 
    if not data["matches"]: 
     self.logger.info("processing done") 
     return 
    for x in data["matches"]: 
     yield self.process_your_item(x) 
    self.offset += 100 
    yield self.next_request() 
+0

謝謝!我編輯了'start_urls'屬性,以便至少處理一個項目+由於我們在'parse'方法中做了所有的事情,所以'next_request'回調中不需要。 – Helvdan