今日內容 scrapy的使用 提高爬蟲效率
-
scrapy架構介紹
引擎(ENGINE)
引擎負責控制系統所有元件之間的資料流,並在某些動作發生時觸發事件。有關詳細資訊,請參見上面的資料流部分
排程器(SCHEDULER)
用來接收引擎發過來的請求,壓入佇列中,並在引擎再次請求的時候返回,可以想象成一個URL的優先順序佇列,由它來決定下一個要抓取的網址是什麼,同時去除重複的網址
下載器(DOWLOADER)
用於下載網頁內容,並 將網頁內容返回給ENGINE,下載器是建立在twisted這個高效的非同步模型上的
爬蟲(SPIDERS)>>>在這裡寫程式碼
SPIDERS是開發人員自定義的類,用來解析response,並且提取items,或者傳送新的請求
專案管道(ITEM PIPLINES)
在items被提取後負責處理它們,主要包括清理,驗證,持久化(比如存到資料庫)等操作
下載器中介軟體(Downloader Middlewares)
位於Scrapy引擎和下載器之間,主要用來處理從ENGINE傳到DOWLOADER的請求request,已經從DOWNLOADER傳到EGINE的響應response,你可用該中介軟體做以下幾件事:設定請求頭,設定cookie,使用代理,整合selenium、
爬蟲中介軟體(Spider Middlewares)
位於ENGINE和SPIDERS之間,主要工作是處理SPIDERS的輸入(即response)和輸出(即requests)
-
scrapy解析資料
response物件有css方法和xpath方法
css中寫css選擇器
xpath中寫xpath選擇器
xpath取文字內容
'.//a[contains(@class,"link-title")]/text()'
xpath取屬性
'.//a[contains(@class,"link-title")]/@href'
xpath取文字
'a.link-title::text'
css取屬性
'img.image-scale::attr(src)'
取一個
.extract_first()
取所有
.extract()
class CnblogsSpider(scrapy.Spider): name = 'cnblogs' allowed_domains = ['www.cnblogs.com'] start_urls = ['http://www.cnblogs.com/'] def parse(self, response): # response類似於requests模組的response物件 # print(response.text) # 返回的資料,解析資料: # 方式一:使用bs4(不用了) # soup=BeautifulSoup(response.text,'lxml') # article_list=soup.find_all(class_='post-item') # for article in article_list: # title_name=article.find(name='a',class_='post-item-title').text # print(title_name) # 方式二:scrapy自帶的解析(css,xpath) # css解析 # article_list = response.css('article.post-item') # for article in article_list: # title_name = article.css('section>div>a::text').extract_first() # author_img = article.css('p.post-item-summary>a>img::attr(src)').extract_first() # desc_list = article.css('p.post-item-summary::text').extract() # desc = desc_list[0].replace('\n', '').replace(' ', '') # if not desc: # desc = desc_list[1].replace('\n', '').replace(' ', '') # # author_name = article.css('section>footer>a>span::text').extract_first() # article_date = article.css('section>footer>span>span::text').extract_first() # # 文章詳情內容,因為在下一頁,先不著急 # print(''' # 文章標題:%s # 作者頭像:%s # 摘要:%s # 作者名字:%s # 釋出日期:%s # ''' % (title_name, author_img, desc, author_name, article_date)) #xpath選擇器 article_list = response.xpath('//article[contains(@class,"post-item")]') for article in article_list: title_name = article.xpath('./section/div/a/text()').extract_first() author_img = article.xpath('./section/div/p//img/@src').extract_first() desc_list = article.xpath('./section/div/p/text()').extract() desc = desc_list[0].replace('\n', '').replace(' ', '') if not desc: desc = desc_list[1].replace('\n', '').replace(' ', '') author_name = article.xpath('./section/footer/a/span/text()').extract_first() article_date = article.xpath('./section/footer/span/span/text()').extract_first() # 文章詳情內容,因為在下一頁,先不著急 print(''' 文章標題:%s 作者頭像:%s 摘要:%s 作者名字:%s 釋出日期:%s ''' % (title_name,author_img,desc,author_name,article_date))
-
settings相關配置,提高爬取效率
基礎的一些
#1 是否遵循爬蟲協議
ROBOTSTXT_OBEY = False
#2 LOG_LEVEL 日誌級別
LOG_LEVEL='ERROR' # 報錯如果不列印日誌,在控制檯看不到錯誤
# 3 USER_AGENT
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
# 4 DEFAULT_REQUEST_HEADERS 預設請求頭
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# 5 SPIDER_MIDDLEWARES 爬蟲中介軟體
#SPIDER_MIDDLEWARES = {
# 'cnblogs.middlewares.CnblogsSpiderMiddleware': 543,
#}
# 6 DOWNLOADER_MIDDLEWARES 下載中介軟體
#DOWNLOADER_MIDDLEWARES = {
# 'cnblogs.middlewares.CnblogsDownloaderMiddleware': 543,
#}
# 7 ITEM_PIPELINES 持久化配置
#ITEM_PIPELINES = {
# 'cnblogs.pipelines.CnblogsPipeline': 300,
#}
#8 爬蟲專案名字
BOT_NAME = 'myfirstscrapy'
#9 指定爬蟲類的py檔案的位置
SPIDER_MODULES = ['myfirstscrapy.spiders']
NEWSPIDER_MODULE = 'myfirstscrapy.spiders'
增加爬蟲的爬取效率
方法1 增加併發 預設16:
預設scrapy開啟的併發執行緒為32個,可以適當進行增加。在settings配置檔案中修改
方法2 降低日誌級別:
在執行scrapy時,會有大量日誌資訊的輸出,為了減少CPU的使用率。可以設定log輸出資訊為INFO或者ERROR即可,在配置檔案中編寫:LOG_LEVEL = 'INFO'
方法3 禁止cookie
如果不是真的需要cookie,則在srcapy爬取資料時可以禁止cookie從而減少CPU的使用率,提取爬取效率。在配置檔案中編寫:COOKIES_ENABLED = False
方法4 禁止重試
對失敗的HTTP進行重新請求(重試)會減慢爬取速度,因此可以禁止重試。在配置檔案中編寫:RETRY_ENABLED = False
方法5 減少下載超時
如果對一個非常慢的連結進行爬取,減少下載超時可以能讓卡住的連結快速被放棄,從而提升效率。在配置檔案中編寫:DOWNLOAD_TIMEOUT = 10 # 超時時間為10s
-
持久化方案
# 儲存到硬碟上---》持久化
# 兩種方案,第二種常用
-第一種:瞭解
-解析函式中parse,要return [{},{},{}]
-scrapy crawl cnblogs -o 檔名(json,pickle,csv結尾)
-方案二:使用pipline 常用的,管道形式,可以同時存到多個位置的
-1 在items.py中寫一個類[相當於寫django的表模型],繼承scrapy.Item
-2 在類中寫屬性,寫欄位,所有欄位都是scrapy.Field型別
title = scrapy.Field()
-3 在爬蟲中匯入類,例項化得到物件,把要儲存的資料放到物件中
item['title'] = title 【不要使用. 放】
解析類中 yield item
-4 修改配置檔案,指定pipline,數字表示優先順序,越小越大
ITEM_PIPELINES = {
'crawl_cnblogs.pipelines.CrawlCnblogsPipeline': 300,
}
-5 寫一個pipline:CrawlCnblogsPipeline
-open_spider:資料初始化,開啟檔案,開啟資料庫連結
-process_item:真正儲存的地方
-一定不要忘了return item,交給後續的pipline繼續使用
-close_spider:銷燬資源,關閉檔案,關閉資料庫連結
-
全站爬取cnblogs文章
# 第一頁爬完後,要儲存的資料已經儲存了
#接下來要做兩個事:
1 繼續爬取下一頁:解析出下一頁的地址,包裝成request物件
2 繼續爬取詳情頁:解析出詳情頁地址,包裝成request物件
# 現在在這不能儲存了,因為資料不全,缺了文章詳情,把文章詳情加入後,再一次性儲存
request和response物件傳遞引數
# Request建立:在parse中,for迴圈中,建立Request物件時,傳入meta
yield Request(url=url, callback=self.detail_parse,meta={'item':item})
# Response物件:detail_parse中,通過response取出meta取出item,把文章詳情寫入
yield item
解析下一頁並繼續爬取
import scrapy
from bs4 import BeautifulSoup
from myfirstscrapy.items import CnblogsItem
from scrapy import Request
# from scrapy.http.request import Request
class CnblogsSpider(scrapy.Spider):
name = 'cnblogs'
allowed_domains = ['www.cnblogs.com']
start_urls = ['http://www.cnblogs.com/']
def parse(self, response):
# item = CnblogsItem() # 外面定義,會有問題
article_list = response.xpath('//article[contains(@class,"post-item")]')
for article in article_list:
item = CnblogsItem() # 定義在for內部,每次都是一個新物件
title_name = article.xpath('./section/div/a/text()').extract_first()
author_img = article.xpath('./section/div/p//img/@src').extract_first()
desc_list = article.xpath('./section/div/p/text()').extract()
desc = desc_list[0].replace('\n', '').replace(' ', '')
if not desc:
desc = desc_list[1].replace('\n', '').replace(' ', '')
author_name = article.xpath('./section/footer/a/span/text()').extract_first()
article_date = article.xpath('./section/footer/span/span/text()').extract_first()
url = article.xpath('./section/div/a/@href').extract_first()
# 文章詳情內容,因為在下一頁,先不著急
item['title_name'] = title_name
item['author_img'] = author_img
item['desc'] = desc
item['author_name'] = author_name
item['article_date'] = article_date
item['url'] = url
# print(url)
# 現在不存了,因為資料不全,等全了以後再存,繼續爬取,就要建立Request物件
# 詳情頁面,使用self.detail_parse解析
yield Request(url=url, callback=self.detail_parse,meta={'item':item})
# 解析出下一頁地址
# css
next_url = 'https://www.cnblogs.com' + response.css('div.pager>a:last-child::attr(href)').extract_first()
print(next_url)
yield Request(url=next_url, callback=self.parse)
def detail_parse(self, response):
# print(len(response.text))
item=response.meta.get('item')
# 解析詳情
article_content=response.css('div.post').extract_first()
# print(article_content)
# print('===================')
# 把詳情,寫入當前meta中得item中
item['article_content']=str(article_content)
yield item
-
爬蟲和下載中介軟體
# scrapy的所有中介軟體都寫在middlewares.py中,跟djagno非常像,做一些攔截
# 爬蟲中介軟體(用的很少,瞭解即可)
MyfirstscrapySpiderMiddleware
def process_spider_input(self, response, spider): # 進入爬蟲會執行它
def process_spider_output(self, response, result, spider): #從爬蟲出來會執行它
def process_spider_exception(self, response, exception, spider):#出了異常會執行
def process_start_requests(self, start_requests, spider):#第一次爬取執行
def spider_opened(self, spider): #爬蟲開啟執行
# 下載中介軟體
MyfirstscrapyDownloaderMiddleware
def process_request(self, request, spider): # request物件從引擎進入到下載器會執行
def process_response(self, request, response, spider):# response物件從下載器進入到引擎會執行
def process_exception(self, request, exception, spider):#出異常執行它
def spider_opened(self, spider): #爬蟲開啟執行它
#重點:process_request,process_response
# 下載中介軟體的process_request
-返回值:
- return None: 繼續執行下面的中介軟體的process_request
- return a Response object: 不進入下載中介軟體了,直接返回給引擎,引擎把它通過6給爬蟲
- return a Request object:不進入中介軟體了,直接返回給引擎,引擎把它放到排程器中
- raise IgnoreRequest: process_exception() 拋異常,會執行process_exception
# 下載中介軟體的process_response
-返回值:
- return a Response object:正常,會進入到引擎,引擎把它給爬蟲
- return a Request object: 會進入到引擎,引擎把它放到排程器中,等待下次爬取
- raise IgnoreRequest 會執行process_exception