Python的Scrapy框架中的CrawlSpider介紹和使用
一、介紹CrawlSpider
CrawlSpider其實(shí)是Spider的一個子類,除了繼承到Spider的特性和功能外,還派生除了其自己獨(dú)有的更加強(qiáng)大的特性和功能。其中最顯著的功能就是”LinkExtractors鏈接提取器“。
Spider是所有爬蟲的基類,其設(shè)計原則只是為了爬取start_url列表中網(wǎng)頁,而從爬取到的網(wǎng)頁中提取出的url進(jìn)行繼續(xù)的爬取工作使用CrawlSpider更合適。
源碼:
class CrawlSpider(Spider): rules = () def __init__(self, *a, **kw): super(CrawlSpider, self).__init__(*a, **kw) self._compile_rules() #首先調(diào)用parse()來處理start_urls中返回的response對象 #parse()則將這些response對象傳遞給了_parse_response()函數(shù)處理,并設(shè)置回調(diào)函數(shù)為parse_start_url() #設(shè)置了跟進(jìn)標(biāo)志位True #parse將返回item和跟進(jìn)了的Request對象 def parse(self, response): return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True) #處理start_url中返回的response,需要重寫 def parse_start_url(self, response): return [] def process_results(self, response, results): return results #從response中抽取符合任一用戶定義'規(guī)則'的鏈接,并構(gòu)造成Resquest對象返回 def _requests_to_follow(self, response): if not isinstance(response, HtmlResponse): return seen = set() #抽取之內(nèi)的所有鏈接,只要通過任意一個'規(guī)則',即表示合法 for n, rule in enumerate(self._rules): links = [l for l in rule.link_extractor.extract_links(response) if l not in seen] #使用用戶指定的process_links處理每個連接 if links and rule.process_links: links = rule.process_links(links) #將鏈接加入seen集合,為每個鏈接生成Request對象,并設(shè)置回調(diào)函數(shù)為_repsonse_downloaded() for link in links: seen.add(link) #構(gòu)造Request對象,并將Rule規(guī)則中定義的回調(diào)函數(shù)作為這個Request對象的回調(diào)函數(shù) r = Request(url=link.url, callback=self._response_downloaded) r.meta.update(rule=n, link_text=link.text) #對每個Request調(diào)用process_request()函數(shù)。該函數(shù)默認(rèn)為indentify,即不做任何處理,直接返回該Request. yield rule.process_request(r) #處理通過rule提取出的連接,并返回item以及request def _response_downloaded(self, response): rule = self._rules[response.meta['rule']] return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow) #解析response對象,會用callback解析處理他,并返回request或Item對象 def _parse_response(self, response, callback, cb_kwargs, follow=True): #首先判斷是否設(shè)置了回調(diào)函數(shù)。(該回調(diào)函數(shù)可能是rule中的解析函數(shù),也可能是 parse_start_url函數(shù)) #如果設(shè)置了回調(diào)函數(shù)(parse_start_url()),那么首先用parse_start_url()處理response對象, #然后再交給process_results處理。返回cb_res的一個列表 if callback: #如果是parse調(diào)用的,則會解析成Request對象 #如果是rule callback,則會解析成Item cb_res = callback(response, **cb_kwargs) or () cb_res = self.process_results(response, cb_res) for requests_or_item in iterate_spider_output(cb_res): yield requests_or_item #如果需要跟進(jìn),那么使用定義的Rule規(guī)則提取并返回這些Request對象 if follow and self._follow_links: #返回每個Request對象 for request_or_item in self._requests_to_follow(response): yield request_or_item def _compile_rules(self): def get_method(method): if callable(method): return method elif isinstance(method, basestring): return getattr(self, method, None) self._rules = [copy.copy(r) for r in self.rules] for rule in self._rules: rule.callback = get_method(rule.callback) rule.process_links = get_method(rule.process_links) rule.process_request = get_method(rule.process_request) def set_crawler(self, crawler): super(CrawlSpider, self).set_crawler(crawler) self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)
文檔:Spiders — Scrapy 2.9.0 documentation
二、框架搭建
1.創(chuàng)建scrapy框架工程
scrapy startproject Meitou
2.進(jìn)入工程目錄
cd Meitou
3.創(chuàng)建爬蟲文件
scrapy genspider -t crawl 爬蟲任務(wù)名稱 爬取的范圍域 scrapy genspider -t crawl crawl_yjin xx.com
此指令對比以前指令多了"-t crawl",表示創(chuàng)建的爬蟲文件是基于CrawlSpider這個類的,而不再是Spider這個基類。
4.啟動爬蟲文件
scrapy crawl crawl_yjin --nolog
(一)、查看生成的爬蟲文件:
Rule(規(guī)則): 規(guī)范url構(gòu)造請求對象的規(guī)則
LinkExtractor(鏈接提取器):規(guī)范url的提取范圍
CrawlSpider:是一個類模板,繼承自Spider,功能就更加的強(qiáng)大
(二)、查看LinkExtractor源碼:
LinkExtractor 鏈接提取器
作用:提取response中符合規(guī)則的鏈接。
主要參數(shù)含義:
- LinkExtractor:規(guī)范url提取可用的部分
- allow=(): 滿足括號中“正則表達(dá)式”的值會被提取,如果為空,則全部匹配。
- deny=(): 與這個正則表達(dá)式(或正則表達(dá)式列表)不匹配的URL一定不提取。
- allow_domains=():允許的范圍域
- deny_domains=(): 不允許的范圍域
- restrict_xpaths=(): 使用xpath表達(dá)式,和allow共同作用過濾鏈接(只選到節(jié)點(diǎn),不選到屬性)
- tags=('a', 'area'): 指定標(biāo)簽
- attrs=('href',): 指定屬性
(三)、查看Rule源碼:
Rule : 規(guī)則解析器。根據(jù)鏈接提取器中提取到的鏈接,根據(jù)指定規(guī)則提取解析器鏈接網(wǎng)頁中的內(nèi)容
Rule (LinkExtractor(allow=r"Items/"), callback="parse_item", follow=True)
主要參數(shù)含義:
- link_extractor為LinkExtractor,用于定義需要提取的鏈接
- callback參數(shù):當(dāng)link_extractor獲取到鏈接時參數(shù)所指定的值作為回調(diào)函數(shù)
- callback參數(shù)使用注意: 當(dāng)編寫爬蟲規(guī)則時,請避免使用parse作為回調(diào)函數(shù)。于CrawlSpider使用parse方法來實(shí)現(xiàn)其邏輯,如果您覆蓋了parse方法,crawlspider將會運(yùn)行失敗
- follow:指定了根據(jù)該規(guī)則從response提取的鏈接是否需要跟進(jìn)。 當(dāng)callback為None,默認(rèn)值為True
- process_links:主要用來過濾由link_extractor獲取到的鏈接
- process_request:主要用來過濾在rule中提取到的request
rules=( ):指定不同規(guī)則解析器。一個Rule對象表示一種提取規(guī)則。
(四)、CrawlSpider整體爬取流程:
(a) 爬蟲文件首先根據(jù)起始url,獲取該url的網(wǎng)頁內(nèi)容
(b) 鏈接提取器會根據(jù)指定提取規(guī)則將步驟a中網(wǎng)頁內(nèi)容中的鏈接進(jìn)行提取
(c) 規(guī)則解析器會根據(jù)指定解析規(guī)則將鏈接提取器中提取到的鏈接中的網(wǎng)頁內(nèi)容根據(jù)指定的規(guī)則進(jìn)行解析
(d) 將解析數(shù)據(jù)封裝到item中,然后提交給管道進(jìn)行持久化存儲
三、基于CrawlSpider使用
(1)spider爬蟲文件代碼
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class CrawlYjinSpider(CrawlSpider): name = "crawl_yjin" allowed_domains = ["xiachufang.com"] start_urls = ["https://www.xiachufang.com/category/40073/"] # 起始url (分類列表的小吃) # 創(chuàng)建一個Rule對象(也創(chuàng)建一個LinkExtractor對象) rules = ( # 菜單詳情地址 # https://www.xiachufang.com/recipe/106909278/ # https://www.xiachufang.com/recipe/1055105/ Rule(LinkExtractor(allow=r".*?/recipe/\d+/$"), callback="parse_item", follow=False), ) # 解析菜單詳情 def parse_item(self, response): # 不需要手動構(gòu)造item對象 item = {} # print(response.url) # 圖片鏈接,名稱,評分,多少人做過,發(fā)布人 item['imgs'] = response.xpath('//div/img/@src').get() #去除空格和\n item['title']=''.join(response.xpath('//div/h1/text()').get()).replace(' ','').replace('\n','') item['score']=response.xpath('//div[@class="score float-left"]/span[@class="number"]/text()').extract_first() item['number']=response.xpath('//div[@class="cooked float-left"]/span[@class="number"]/text()').get() item['author']=''.join(response.xpath('//div[@class="author"]/a/img/@alt').get()).replace('的廚房','') # print(item) return item
(2)數(shù)據(jù)保存>>pipelines管道文件
import json from itemadapter import ItemAdapter class MeitouPipeline: """處理items對象的數(shù)據(jù)""" def __init__(self): self.file_=open('xcf-1.json','w',encoding='utf-8') print('文件打開了。。。') def process_item(self, item, spider): """item接收爬蟲器丟過來的items對象""" py_dict=dict(item) # 先把攜帶鍵值對數(shù)據(jù)items對象轉(zhuǎn)成字典 #dict轉(zhuǎn)換成json數(shù)據(jù) json_data=json.dumps(py_dict,ensure_ascii=False)+",\n" #寫入 self.file_.write(json_data) print("寫入數(shù)據(jù)...") return item def __del__(self): self.file_.close() #關(guān)閉 print('文件關(guān)閉了....')
(3)settings相關(guān)設(shè)置 >>settings.py設(shè)置文件
# 全局用戶代理,默認(rèn)是被注釋了,不生效 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False # 設(shè)置下載延時 DOWNLOAD_DELAY = 1 #開啟管道 ITEM_PIPELINES = { "Meitou.pipelines.MeitouPipeline": 300, }
(4)運(yùn)行程序 >>scrapy crawl crawl_yjin --nolog
查看保存的json文件
到此這篇關(guān)于Python的Scrapy框架中的CrawlSpider介紹和使用的文章就介紹到這了,更多相關(guān)Scrapy框架中的CrawlSpider 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python調(diào)用jenkinsAPI構(gòu)建jenkins,并傳遞參數(shù)的示例
這篇文章主要介紹了python調(diào)用jenkinsAPI構(gòu)建jenkins,并傳遞參數(shù)的示例,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-12-12Python?Pytorch學(xué)習(xí)之圖像檢索實(shí)踐
隨著電子商務(wù)和在線網(wǎng)站的出現(xiàn),圖像檢索在我們的日常生活中的應(yīng)用一直在增加。圖像檢索的基本本質(zhì)是根據(jù)查詢圖像的特征從集合或數(shù)據(jù)庫中查找圖像。本文將利用Pytorch實(shí)現(xiàn)圖像檢索,需要的可以參考一下2022-04-04python進(jìn)階之多線程對同一個全局變量的處理方法
今天小編就為大家分享一篇python進(jìn)階之多線程對同一個全局變量的處理方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11python實(shí)現(xiàn)pdf轉(zhuǎn)word和excel的示例代碼
本文主要介紹了python實(shí)現(xiàn)pdf轉(zhuǎn)word和excel的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01python實(shí)現(xiàn)代碼審查自動回復(fù)消息
這篇文章主要介紹了python實(shí)現(xiàn)代碼審查回復(fù)消息生成的示例,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2021-02-02python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫的完整代碼
這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02python?os.stat()如何獲取相關(guān)文件的系統(tǒng)狀態(tài)信息
這篇文章主要介紹了python?os.stat()如何獲取相關(guān)文件的系統(tǒng)狀態(tài)信息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11使用 django orm 寫 exists 條件過濾實(shí)例
這篇文章主要介紹了使用 django orm 寫 exists 條件過濾實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05