標籤:python scrapy 遞迴 parse yield
scrapy spider的parse方法可以返回兩種值:BaseItem,或者Request。通過Request可以實現遞迴抓取。
如果要抓取的資料在當前頁,可以直接解析返回item(代碼中帶**注釋的行直接改為yield item);
如果要抓取的資料在當前頁指向的頁面,則返回Request並指定parse_item作為callback;
如果要抓取的資料當前頁有一部分,指向的頁面有一部分(比如部落格或論壇,當前頁有標題、摘要和url,詳情頁面有完整內容)這種情況需要用Request的meta參數把當前頁面解析到的資料傳到parse_item,後者繼續解析item剩下的資料。
要抓完當前頁再抓其它頁面(比如下一頁),可以返回Request,callback為parse。
有點奇怪的是:parse不能返回item列表,但作為callback的parse_item卻可以,不知道為啥。
另外,直接extract()得到的文字不包含<a>等子標籤的內容,可改為d.xpath(‘node()‘).extract(),得到的是包含html的文本,再過濾掉標籤就是純文字了。
沒找到直接得到html的方法。
from scrapy.spider import Spiderfrom scrapy.selector import Selectorfrom dirbot.items import Articleimport jsonimport reimport stringfrom scrapy.http import Requestclass YouyousuiyueSpider(Spider): name = "youyousuiyue2" allowed_domains = ["youyousuiyue.sinaapp.com"] start_urls = [ 'http://youyousuiyue.sinaapp.com', ] def load_item(self, d): item = Article() title = d.xpath('header/h1/a') item['title'] = title.xpath('text()').extract() print item['title'][0] item['url'] = title.xpath('@href').extract() return item def parse_item(self, response): item = response.meta['item'] sel = Selector(response) d = sel.xpath('//div[@class="entry-content"]/div') item['content'] = d.xpath('text()').extract() return item def parse(self, response): """ The lines below is a spider contract. For more info see: http://doc.scrapy.org/en/latest/topics/contracts.html @url http://youyousuiyue.sinaapp.com @scrapes name """ print 'parsing ', response.url sel = Selector(response) articles = sel.xpath('//div[@id="content"]/article') for d in articles: item = self.load_item(d) yield Request(item['url'][0], meta={'item':item}, callback=self.parse_item) # ** or yield item sel = Selector(response) link = sel.xpath('//div[@class="nav-previous"]/a/@href').extract()[0] if link[-1] == '4': return else: print 'yielding ', link yield Request(link, callback=self.parse)
詳細代碼見:https://github.com/junglezax/dirbot
參考:
http://doc.scrapy.org/en/latest/intro/tutorial.html
http://www.icultivator.com/p/3166.html