scrapy遞迴抓取網頁資料

來源:互聯網
上載者:User

標籤: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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.