scrapy之CrawlSpider

簡(jiǎn)介

class scrapy.spiders.CrawlSpider

CrawlSpider是爬取一般網(wǎng)站常用的spider,適合于從爬取的網(wǎng)頁(yè)中獲取link并繼續(xù)爬取的場(chǎng)景。
除了從Spider繼承過(guò)來(lái)的性外,其提供了一個(gè)新的屬性rules,它是一個(gè)Rule對(duì)象列表,每個(gè)Rule對(duì)象定義了種義link的提取規(guī)則,如果多個(gè)Rule匹配一個(gè)連接,那么根據(jù)定義的順序使用第一個(gè)。

例子

from coolscrapy.items import HuxiuItem
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class LinkSpider(CrawlSpider):
    name = "link"
    allowed_domains = ["huxiu.com"]
    start_urls = [
        "http://www.huxiu.com/index.php"
    ]

    rules = (
        # 提取匹配正則式'/group?f=index_group'鏈接 (但是不能匹配'deny.php')
        # 并且會(huì)遞歸爬取(如果沒(méi)有定義callback,默認(rèn)follow=True).
        Rule(LinkExtractor(allow=('/group?f=index_group', ), deny=('deny\.php', ))),
        # 提取匹配'/article/\d+/\d+.html'的鏈接,并使用parse_item來(lái)解析它們下載后的內(nèi)容,不遞歸
        Rule(LinkExtractor(allow=('/article/\d+/\d+\.html', )), callback='parse_item'),
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)
        detail = response.xpath('//div[@class="article-wrap"]')
        item = HuxiuItem()
        item['title'] = detail.xpath('h1/text()')[0].extract()
        item['link'] = response.url
        item['posttime'] = detail.xpath(
            'div[@class="article-author"]/span[@class="article-time"]/text()')[0].extract()
        print(item['title'],item['link'],item['posttime'])
        yield item

詳解

 class scrapy.spiders.Rule(link_extractor, callback=None, cb_kwargs=None, follow=None, process_links=None, process_request=None)

主要參數(shù):
link_extractor是一個(gè)Link Extractor對(duì)象。 其定義了如何從爬取到的頁(yè)面提取鏈接。

callback參數(shù):當(dāng)link_extractor獲取到鏈接時(shí)會(huì)調(diào)用該參數(shù)所指定的回調(diào)函數(shù). 該回調(diào)函數(shù)接受一個(gè)response作為其第一個(gè)參數(shù), 并返回一個(gè)包含 Item 以及(或) Request 對(duì)象(或者這兩者的子類(lèi))的列表(list)。
callback參數(shù)使用注意:當(dāng)編寫(xiě)爬蟲(chóng)規(guī)則時(shí),請(qǐng)避免使用parse作為回調(diào)函數(shù)。于CrawlSpider使用parse方法來(lái)實(shí)現(xiàn)其邏輯,如果您覆蓋了parse方法,crawlspider將會(huì)運(yùn)行失敗。

cb_kwargs:包含傳遞給回調(diào)函數(shù)的參數(shù)(keyword argument)的字典。
follow:指定了根據(jù)該規(guī)則從response提取的鏈接是否需要繼續(xù)跟進(jìn)。當(dāng)callback為None, 默認(rèn)值為T(mén)rue。
process_links:主要用來(lái)過(guò)濾由link_extractor獲取到的鏈接。
process_request:主要用來(lái)過(guò)濾在rule中提取到的request。

 class scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor(allow=(), deny=(), allow_domains=(), deny_domains=(), deny_extensions=None, restrict_xpaths=(), restrict_css=(), tags=('a', 'area'), attrs=('href', ), canonicalize=True, unique=True, process_value=None)

主要參數(shù):
allow:滿(mǎn)足這個(gè)正則表達(dá)式(或正則表達(dá)式列表)的URL會(huì)被提取,如果為空,則全部匹配。
deny:滿(mǎn)足這個(gè)正則表達(dá)式(或正則表達(dá)式列表)的URL一定不提取。如果為空,不過(guò)濾任何URL。
allow_domains:會(huì)被提取的鏈接的domains(或domains列表)。
deny_domains:一定不會(huì)被提取鏈接的domains(或domains列表)。
deny_extensions: 需要忽略的url擴(kuò)展名列表,如"bmp", "gif", "jpg", "mp3", "wav", "mp4", "wmv"。默認(rèn)使用在模塊scrapy.linkextractors中定義的IGNORED_EXTENSIONS。
restrict_xpaths:指定提取URL的xpath(或xpath列表)。若不為空,則只使用該參數(shù)去提取URL。和allow共同作用過(guò)濾鏈接。
restrict_css:指定提取URL的css列表。若不為空,則只使用該參數(shù)去提取URL
tags:指定提取URL的頁(yè)面tag列表。默認(rèn)為('a','area')
attrs:從tags參數(shù)中指定的tag上提取attrs。默認(rèn)為('href')
canonicalize:是否標(biāo)準(zhǔn)化每個(gè)URL,使用scrapy.utils.url.canonicalize_url。默認(rèn)為T(mén)rue。
unique:是否過(guò)濾提取過(guò)的URL
process_value:處理tags和attrs提取到的URL

scrapy shell中測(cè)試Link Extractor

scrapy shell "http://blog.csdn.net/u012150179/article/details/11749017"
from scrapy.linkextractors import LinkExtractor
item = LinkExtractor(allow=('/u012150179/article/details')).extract_links(response)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容