簡介
class scrapy.spiders.CrawlSpider
CrawlSpider是爬取一般網站常用的spider,適合于從爬取的網頁中獲取link并繼續爬取的場景。
除了從Spider繼承過來的性外,其提供了一個新的屬性rules,它是一個Rule對象列表,每個Rule對象定義了種義link的提取規則,如果多個Rule匹配一個連接,那么根據定義的順序使用第一個。
例子
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')
# 并且會遞歸爬取(如果沒有定義callback,默認follow=True).
Rule(LinkExtractor(allow=('/group?f=index_group', ), deny=('deny\.php', ))),
# 提取匹配'/article/\d+/\d+.html'的鏈接,并使用parse_item來解析它們下載后的內容,不遞歸
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)
主要參數:
link_extractor是一個Link Extractor對象。 其定義了如何從爬取到的頁面提取鏈接。
callback參數:當link_extractor獲取到鏈接時會調用該參數所指定的回調函數. 該回調函數接受一個response作為其第一個參數, 并返回一個包含 Item 以及(或) Request 對象(或者這兩者的子類)的列表(list)。
callback參數使用注意:當編寫爬蟲規則時,請避免使用parse作為回調函數。于CrawlSpider使用parse方法來實現其邏輯,如果您覆蓋了parse方法,crawlspider將會運行失敗。
cb_kwargs:包含傳遞給回調函數的參數(keyword argument)的字典。
follow:指定了根據該規則從response提取的鏈接是否需要繼續跟進。當callback為None, 默認值為True。
process_links:主要用來過濾由link_extractor獲取到的鏈接。
process_request:主要用來過濾在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)
主要參數:
allow:滿足這個正則表達式(或正則表達式列表)的URL會被提取,如果為空,則全部匹配。
deny:滿足這個正則表達式(或正則表達式列表)的URL一定不提取。如果為空,不過濾任何URL。
allow_domains:會被提取的鏈接的domains(或domains列表)。
deny_domains:一定不會被提取鏈接的domains(或domains列表)。
deny_extensions: 需要忽略的url擴展名列表,如"bmp", "gif", "jpg", "mp3", "wav", "mp4", "wmv"。默認使用在模塊scrapy.linkextractors中定義的IGNORED_EXTENSIONS。
restrict_xpaths:指定提取URL的xpath(或xpath列表)。若不為空,則只使用該參數去提取URL。和allow共同作用過濾鏈接。
restrict_css:指定提取URL的css列表。若不為空,則只使用該參數去提取URL
tags:指定提取URL的頁面tag列表。默認為('a','area')
attrs:從tags參數中指定的tag上提取attrs。默認為('href')
canonicalize:是否標準化每個URL,使用scrapy.utils.url.canonicalize_url。默認為True。
unique:是否過濾提取過的URL
process_value:處理tags和attrs提取到的URL
scrapy shell中測試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)