scrapy遞歸抓取網頁數據


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 Spider
from scrapy.selector import Selector

from dirbot.items import Article

import json
import re
import string
from scrapy.http import Request

class 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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM