23. Scrapy 框架-CrawlSpider
原理圖

通過下面的命令可以快速創(chuàng)建 CrawlSpider模板 的代碼
scrapy genspider -t crawl 文件名 (allowed_url)
首先在說下Spider,它是所有爬蟲的基類,而CrawSpiders就是Spider的派生類。對于設計原則是只爬取start_url列表中的網頁,而從爬取的網頁中獲取link并繼續(xù)爬取的工作CrawlSpider類更適合
2. Rule對象
Rule類與CrawlSpider類都位于scrapy.contrib.spiders模塊中
class scrapy.contrib.spiders.Rule ( ?
link_extractor, callback=None,cb_kwargs=None,follow=None,process_links=None,process_request=None )
參數(shù)含義:
link_extractor為LinkExtractor,用于定義需要提取的鏈接
callback參數(shù):當link_extractor獲取到鏈接時參數(shù)所指定的值作為回調函數(shù)
callback參數(shù)使用注意: 當編寫爬蟲規(guī)則時,請避免使用parse作為回調函數(shù)。于CrawlSpider使用parse方法來實現(xiàn)其邏輯,如果您覆蓋了parse方法,crawlspider將會運行失敗
follow:指定了根據該規(guī)則從response提取的鏈接是否需要跟進。當callback為None,默認值為True
process_links:主要用來過濾由link_extractor獲取到的鏈接
process_request:主要用來過濾在rule中提取到的request
3.LinkExtractors
3.1 概念
顧名思義,鏈接提取器
3.2 作用
response對象中獲取鏈接,并且該鏈接會被接下來爬取 每個LinkExtractor有唯一的公共方法是 extract_links(),它接收一個 Response 對象,并返回一個 scrapy.link.Link 對象
3.3 使用
class scrapy.linkextractors.LinkExtractor(
? ?allow = (),
? ?deny = (),
? ?allow_domains = (),
? ?deny_domains = (),
? ?deny_extensions = None,
? ?restrict_xpaths = (),
? ?tags = ('a','area'),
? ?attrs = ('href'),
? ?canonicalize = True,
? ?unique = True,
? ?process_value = None
)
主要參數(shù):
allow:滿足括號中“正則表達式”的值會被提取,如果為空,則全部匹配。
deny:與這個正則表達式(或正則表達式列表)不匹配的URL一定不提取。
allow_domains:會被提取的鏈接的domains。
deny_domains:一定不會被提取鏈接的domains。
restrict_xpaths:使用xpath表達式,和allow共同作用過濾鏈接(只選到節(jié)點,不選到屬性)
3.3.1 查看效果(shell中驗證)
首先運行
scrapy shell http://www.fhxiaoshuo.com/read/33/33539/17829387.shtml
繼續(xù)import相關模塊:
from scrapy.linkextractors import LinkExtractor
提取當前網頁中獲得的鏈接
link = LinkExtractor(restrict_xpaths=(r'//div[@class="bottem"]/a[4]')
調用LinkExtractor實例的extract_links()方法查詢匹配結果
link.extract_links(response)
3.3.2 查看效果 CrawlSpider版本
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from xiaoshuo.items import XiaoshuoItem
class XiaoshuoSpiderSpider(CrawlSpider):
? ?name = 'xiaoshuo_spider'
? ?allowed_domains = ['fhxiaoshuo.com']
? ?start_urls = ['http://www.fhxiaoshuo.com/read/33/33539/17829387.shtml']
? ?rules = [
? ? ? ?Rule(LinkExtractor(restrict_xpaths=(r'//div[@class="bottem"]/a[4]')), callback='parse_item'),]
? ?def parse_item(self, response):
? ? ? ?info = response.xpath("//div[@id='TXT']/text()").extract()
? ? ? ?it = XiaoshuoItem()
? ? ? ?it['info'] = info
? ? ? ?yield it
注意:
rules = [
? ? ? ?Rule(LinkExtractor(restrict_xpaths=(r'//div[@class="bottem"]/a[4]')), callback='parse_item'),]
callback后面函數(shù)名用引號引起
函數(shù)名不能是parse