先來(lái)看一下需求约啊,以抓取簡(jiǎn)書(shū)用戶信息為例:
- 用戶主頁(yè)左側(cè)顯示的信息:(用戶主要信息)
- 用戶昵稱(nickname)
- 關(guān)注數(shù)(subs)
- 粉絲(fans)
- 文章(articles)
- 字?jǐn)?shù)(words)
以上數(shù)據(jù)從用戶首頁(yè)可以獲取(/latest_articles)袁串,其他頁(yè)面(/timeline, /followers...)都有這些數(shù)據(jù)彪标。
- 我們還關(guān)注的信息:(反映用戶活躍度的其他數(shù)據(jù))
- 用戶文章總閱讀量(read_nums)
- 用戶獲得打賞數(shù)量(rewards)
- 用戶獲得評(píng)論數(shù)量(comments)
- 用戶發(fā)表的評(píng)論數(shù)量(pub_comments)
- 用戶注冊(cè)時(shí)間(regtime)
以上數(shù)據(jù)在包含在兩個(gè)(類)頁(yè)面中:
1)閱讀量倍权、打賞量、評(píng)論數(shù)量3個(gè)數(shù)據(jù)在latest_articles頁(yè)面上捞烟,需要匯總得到薄声,每頁(yè)中每條(每篇文章)匯總,然后分頁(yè)匯總所有文章的這3個(gè)數(shù)據(jù)题画。
2)用戶發(fā)表的其他評(píng)論和注冊(cè)時(shí)間默辨,在timeline頁(yè)面上,其中用戶發(fā)表的評(píng)論需要在timeline頁(yè)面上每頁(yè)匯總苍息,注冊(cè)時(shí)間在timeline最后一頁(yè)缩幸。
一個(gè)用戶完整的信息要在多個(gè)Request中獲取,需要在請(qǐng)求之間傳遞參數(shù)竞思。
直到該用戶所有頁(yè)面數(shù)據(jù)匯總完成表谊,提交item。
Scrapy采用的是回調(diào)(callback)的方式盖喷,把請(qǐng)求處理交給下一次請(qǐng)求爆办,在請(qǐng)求時(shí)用meta傳遞參數(shù)。Request(url=item_details_url, meta={'item': item},callback=self.parse_details)
课梳,可傳遞簡(jiǎn)單類型參數(shù)或?qū)ο箢愋蛥?shù)距辆。
def parse(self, response):
# collect `item_urls`
for item_url in item_urls:
yield Request(url=item_url, callback=self.parse_item)
def parse_item(self, response):
item = MyItem()
# populate `item` fields 收集處理一部分?jǐn)?shù)據(jù)
yield Request(url=item_details_url, meta={'item': item},
callback=self.parse_details)
def parse_details(self, response):
item = response.meta['item']
# populate more `item` fields 再收集處理另外的數(shù)據(jù)
return item
這樣完成一個(gè)用戶所有數(shù)據(jù)收集余佃,注意以上示例代碼沒(méi)有包含分頁(yè)遞歸調(diào)用。
PS:
- 傳遞多個(gè)參數(shù):
yield Request(url, meta={'item': item, 'rdt': rdt, 'comments':cmt,'rewards':rewards,'total': total, 'curpage': cur}, callback=self.parse)
取出多個(gè)參數(shù)跨算。如果不同url過(guò)來(lái)的加上判斷咙冗。(如針對(duì)分頁(yè))
item = response.meta['item']
rdt = response.meta['rdt']
total = response.meta['total']
cur = int(response.meta['curpage'])
cmt = int(response.meta['comments'])
rewards= int(response.meta['rewards'])