Python爬蟲Scrapy框架CrawlSpider原理及使用案例
提問:如果想要通過爬蟲程序去爬取”糗百“全站數(shù)據(jù)新聞數(shù)據(jù)的話,有幾種實現(xiàn)方法?
方法一:基于Scrapy框架中的Spider的遞歸爬去進行實現(xiàn)的(Request模塊回調(diào))
方法二:基于CrawlSpider的自動爬去進行實現(xiàn)(更加簡潔和高效)
一、簡單介紹CrawlSpider
CrawlSpider其實是Spider的一個子類,除了繼承到Spider的特性和功能外,還派生除了其自己獨有的更加強大的特性和功能。其中最顯著的功能就是”LinkExtractors鏈接提取器“。Spider是所有爬蟲的基類,其設(shè)計原則只是為了爬取start_url列表中網(wǎng)頁,而從爬取到的網(wǎng)頁中提取出的url進行繼續(xù)的爬取工作使用CrawlSpider更合適。
二、使用
1.創(chuàng)建scrapy工程(cmd切換到要創(chuàng)建項目的文件夾下執(zhí)行):scrapy startproject projectName (如:scrapy startproject crawlPro)
2.創(chuàng)建爬蟲文件(cmd切換到創(chuàng)建的項目下執(zhí)行):scrapy genspider -t crawl spiderName www.xxx.com (如:scrapy genspider -t crawl crawlDemo www.qiushibaike.com)
--此指令對比以前的指令多了 '-t crawl',表示創(chuàng)建的爬蟲文件是基于CrawlSpider這個類的,而不再是Spider這個基類。
3.啟動爬蟲文件(cmd基于步驟二的路徑執(zhí)行):scrapy crawl crawlDemo (啟動的一定是name對應(yīng)的值,如果爬蟲文件與name的值不一致,任然以name的值進行啟動)
觀察生成的爬蟲文件
crawlDemo.py
# -*- coding: utf-8 -*-import scrapy# 導(dǎo)入CrawlSpider相關(guān)模塊from scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rule# 表示該爬蟲程序是基于CrawlSpider類的class CrawldemoSpider(CrawlSpider): name = ’crawlDemo’ #爬蟲文件名稱 #allowed_domains = [’www.qiushibaike.com’] start_urls = [’http://www.qiushibaike.com/’] #連接提取器:會去起始url響應(yīng)回來的頁面中提取指定的url link = LinkExtractor(allow=r’/8hr/page/d+’) #rules元組中存放的是不同的規(guī)則解析器(封裝好了某種解析規(guī)則) rules = ( #規(guī)則解析器:可以將連接提取器提取到的所有連接表示的頁面進行指定規(guī)則(回調(diào)函數(shù))的解析 Rule(link, callback=’parse_item’, follow=True), ) # 解析方法 def parse_item(self, response): #print(response.url) divs = response.xpath(’//div[@id='content-left']/div’) for div in divs: author = div.xpath(’./div[@class='author clearfix']/a[2]/h2/text()’).extract_first() print(author)
CrawlSpider類和Spider類的最大不同是CrawlSpider多了一個rules屬性,其作用是定義”提取動作“。在rules中可以包含一個或多個Rule對象,在Rule對象中包含了LinkExtractor對象。
三、生成的爬蟲文件參數(shù)介紹
3.1 LinkExtractor:顧名思義,鏈接提取器。
LinkExtractor(
allow=r’Items/’,# 滿足括號中“正則表達式”的值會被提取,如果為空,則全部匹配。
deny=xxx, # 滿足正則表達式的則不會被提取。
restrict_xpaths=xxx, # 滿足xpath表達式的值會被提取
restrict_css=xxx, # 滿足css表達式的值會被提取
deny_domains=xxx, # 不會被提取的鏈接的domains。
)
- 作用:提取response中符合規(guī)則的鏈接。
3.2 Rule : 規(guī)則解析器。根據(jù)鏈接提取器中提取到的鏈接,根據(jù)指定規(guī)則提取解析器鏈接網(wǎng)頁中的內(nèi)容。
Rule(LinkExtractor(allow=r’Items/’), callback=’parse_item’, follow=True)
- 參數(shù)介紹:
參數(shù)1:指定鏈接提取器
參數(shù)2:指定規(guī)則解析器解析數(shù)據(jù)的規(guī)則(回調(diào)函數(shù))
參數(shù)3:是否將鏈接提取器繼續(xù)作用到鏈接提取器提取出的鏈接網(wǎng)頁中。當callback為None,參數(shù)3的默認值為true。
3.3 rules=( ):指定不同規(guī)則解析器。一個Rule對象表示一種提取規(guī)則。
3.4 CrawlSpider整體爬取流程:
a)爬蟲文件首先根據(jù)起始url,獲取該url的網(wǎng)頁內(nèi)容
b)鏈接提取器會根據(jù)指定提取規(guī)則將步驟a中網(wǎng)頁內(nèi)容中的鏈接進行提取
c)規(guī)則解析器會根據(jù)指定解析規(guī)則將鏈接提取器中提取到的鏈接中的網(wǎng)頁內(nèi)容根據(jù)指定的規(guī)則進行解析
d)將解析數(shù)據(jù)封裝到item中,然后提交給管道進行持久化存儲
四、基于CrawlSpider示例
創(chuàng)建爬蟲項目和啟動爬蟲項目以及settings中配置自行完成,在這里不在追贅述
4.1爬蟲文件
# -*- coding: utf-8 -*-import scrapyfrom scrapy.linkextractors import LinkExtractorfrom scrapy.spiders import CrawlSpider, Rulefrom qiubaiBycrawl.items import QiubaibycrawlItemimport reclass QiubaitestSpider(CrawlSpider): name = ’qiubaiTest’ #起始url start_urls = [’http://www.qiushibaike.com/’] #定義鏈接提取器,且指定其提取規(guī)則 page_link = LinkExtractor(allow=r’/8hr/page/d+/’) rules = ( #定義規(guī)則解析器,且指定解析規(guī)則通過callback回調(diào)函數(shù) Rule(page_link, callback=’parse_item’, follow=True), ) #自定義規(guī)則解析器的解析規(guī)則函數(shù) def parse_item(self, response): div_list = response.xpath(’//div[@id='content-left']/div’)for div in div_list: #定義item item = QiubaibycrawlItem() #根據(jù)xpath表達式提取糗百中段子的作者 item[’author’] = div.xpath(’./div/a[2]/h2/text()’).extract_first().strip(’n’) #根據(jù)xpath表達式提取糗百中段子的內(nèi)容 item[’content’] = div.xpath(’.//div[@class='content']/span/text()’).extract_first().strip(’n’) yield item #將item提交至管道
4.2items文件
# -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass QiubaibycrawlItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() #作者 content = scrapy.Field() #內(nèi)容
4.3管道文件
# -*- coding: utf-8 -*-# Define your item pipelines here## Don’t forget to add your pipeline to the ITEM_PIPELINES setting# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.htmlclass QiubaibycrawlPipeline(object): def __init__(self): self.fp = None def open_spider(self,spider): print(’開始爬蟲’) self.fp = open(’./data.txt’,’w’) def process_item(self, item, spider): #將爬蟲文件提交的item寫入文件進行持久化存儲 self.fp.write(item[’author’]+’:’+item[’content’]+’n’) return item def close_spider(self,spider): print(’結(jié)束爬蟲’) self.fp.close()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. HTML <!DOCTYPE> 標簽2. 5個HTML5的常用本地存儲方式詳解與介紹3. asp在iis7報錯行號不準問題的解決方法4. asp批量添加修改刪除操作示例代碼5. 告別AJAX實現(xiàn)無刷新提交表單6. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法7. HTML中的XML數(shù)據(jù)島記錄編輯與添加8. CSS代碼檢查工具stylelint的使用方法詳解9. 三個不常見的 HTML5 實用新特性簡介10. 原生js XMLhttprequest請求onreadystatechange執(zhí)行兩次的解決
