本篇博客我們將學習如何通過 scrapy 批量下載檔案,還能學習通過密碼解壓縮包?
目標站點分析
本次要采集的目標站點為:【車標網】,最侄訓取的資料是車標的的矢量圖,

在測驗程序中發現,最后下載的壓縮包存在解壓密碼,所以增加一個 通過密碼解壓縮的步驟,
素材的下載地址,比較容易獲取到,通過地址 logo.php?id=119 修改為 download.php?id=119 即可實作,
其中車標串列頁所在的頁面無迭代規則,按照分類獲取即可:
http://www.chebiao.net/domestic.php
http://www.chebiao.net/es.php
http://www.chebiao.net/jsk.php
http://www.chebiao.net/other.php
http://www.chebiao.net/famous.php
撰寫時間
scrapy 基本創建不在過多說明,spider 檔案夾中的爬蟲檔案名為 cb.py,首先通過 start_urls 的設定,采集所有分類資料,
import scrapy
from chebiao.items import ChebiaoItem
from urllib.parse import urlparse
class CbSpider(scrapy.Spider):
name = 'cb'
allowed_domains = ['chebiao.net']
start_urls = ['http://www.chebiao.net/domestic.php', 'http://www.chebiao.net/es.php',
'http://www.chebiao.net/jsk.php', 'http://www.chebiao.net/other.php',
'http://www.chebiao.net/famous.php']
接下來就是重點部分了,我們將啟用 FilesPipeline 管道,用于實作對檔案的下載,
使用該模塊需要匯入如下內容:
from scrapy.pipelines.files import FilesPipeline
FilesPipeline 類繼承自 MediaPipeline,打開類檔案原始碼,在其中發現兩個比較重要的類變數,
DEFAULT_FILES_URLS_FIELD = 'file_urls'
DEFAULT_FILES_RESULT_FIELD = 'files'
上述兩個變數,如果不進行修改,后續在 items.py 檔案中,必須要進行宣告與賦值,
在查看原始碼的程序中,發現了很多可以在 settings.py 檔案初始化的配置,代碼不在整體復制,本文僅用到了 FILES_STORE,即下圖框選區域,該值表示檔案存盤路徑,

FilesPipeline 類中三個比較重要的方法是:
file_path:遍歷item中的每一項,回傳一個檔案存盤地址,函式原型如下所示:
file_path(self, request, response=None, info=None, *, item=None)get_media_requests:遍歷item中的每一項,回傳一個Request請求,請求的結果會傳遞給item_completed方法;item_completed:媒體請求完畢之后,回傳資料到該方法,并且該方法需要回傳item或者drop item,
這里還要補充一個知識點,也是在翻閱 scrapy 原始碼的時候發現的,在 MediaPipeline 類中存在如下私有方法,
def _make_compatible(self):
"""Make overridable methods of MediaPipeline and subclasses backwards compatible"""
methods = [
"file_path", "media_to_download", "media_downloaded",
"file_downloaded", "image_downloaded", "get_images"
]
for method_name in methods:
method = getattr(self, method_name, None)
if callable(method):
setattr(self, method_name, self._compatible(method))
上述代碼將 file_path 與 file_downloaded 方法進行了兼容,即 file_path 與 media_to_download 和 media_downloaded 功能一致,file_downloaded 與 image_downloaded 和 get_images 功能一致,
如果你在測驗代碼時,發現 file_path() 方法被執行了 3 次,該原因也是由于 scrapy 框架實作的,因為 file_path() 方法分別在 media_to_download()、media_downloaded()、file_downloaded() 三個方法中被呼叫過,繼續深入學習,會發現上述 3 個方法的呼叫順序,這里就不在過多展開說明,
通過單檔案下載,測驗 scrapy 下載檔案流程
接下來通過一個檔案,體驗整體的下載流程,該地址為:http://www.chebiao.net/download.php?id=181,
按照一般撰寫爬蟲代碼的順序,修改如下檔案代碼:
items.py 檔案代碼如下
import scrapy
class ChebiaoItem(scrapy.Item):
file_url = scrapy.Field()
file_name = scrapy.Field()
files = scrapy.Field()
其中 file_url 表示請求的檔案名,如果不希望自己擴展,應該用 file_urls 實作,file_name 為保存檔案名,files 為默認欄位,用于回傳檔案回應結果相關資訊,
cb.py 檔案代碼如下
import scrapy
from chebiao.items import ChebiaoItem
class CbSpider(scrapy.Spider):
name = 'cb'
allowed_domains = ['chebiao.net']
start_urls = ['http://www.chebiao.net/famous.php']
def parse(self, response):
item = ChebiaoItem()
item['file_name'] = "測驗" # 檔案名
item['file_url'] = "http://www.chebiao.net/download.php?id=181"
yield item
其中 file_name 與 file_url 都為測驗值,
settings.py 檔案設定爬蟲相關配置
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36' # 用戶代理
ROBOTSTXT_OBEY = False # 不訪問 robot.txt 檔案
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Host': 'www.chebiao.net',
'Referer': 'http://www.chebiao.net/logo.php'
} # 請求頭
# 開啟資料管道,尤其注意 ChebiaoFilePipeline 為我們手動創建的管道類,代碼在下文
ITEM_PIPELINES = {
'chebiao.pipelines.ChebiaoFilePipeline': 1,
'chebiao.pipelines.ChebiaoPipeline': 300,
}
FILES_STORE = './files' # 檔案存盤路徑
LOG_LEVEL = 'WARNING' # 日志等級
配置中的 FILES_STORE 表示檔案存盤路徑,設定絕對地址與相對地址都可,
pipelines.py 代碼檔案
from scrapy.pipelines.files import FilesPipeline
# 自定義類,繼承自 FilesPipeline
class ChebiaoFilePipeline(FilesPipeline):
def get_media_requests(self, item, info):
print("--get_media_requests--start-----")
print("正在下載:", item['file_name'])
print("--get_media_requests--end-----")
# 請求傳遞檔案名引數
yield Request(item['file_url'], meta={'title': item['file_name']})
def file_path(self, request, response=None, info=None):
print("--file_path--start-----")
file_name = request.meta.get('title') + ".rar"
print("--file_path--end-----")
return file_name
def item_completed(self, results, item, info):
print("--item_completed--start-----")
print(results)
print("下載完畢")
print("--item_completed--end--------")
return item
上述代碼中的 item_completed() 方法,還有一層含義,是將資料回傳到下一個要執行的管道類,例如在該方法中為下一個管道增加 items.py 中的引數,需提前在 items.py 中增加 file_paths 變數,
def item_completed(self, results, item, info):
print("--item_completed--start-----")
print(results)
print("下載完畢")
file_paths = [x['path'] for ok, x in results if ok]
adapter = ItemAdapter(item)
adapter['file_paths'] = file_paths
print("--item_completed--end--------")
return item
擴展為多檔案下載
只需要修改 cb.py 檔案即可實作多檔案下載,
import scrapy
from chebiao.items import ChebiaoItem
from urllib.parse import urlparse
class CbSpider(scrapy.Spider):
name = 'cb'
allowed_domains = ['chebiao.net']
start_urls = ['http://www.chebiao.net/domestic.php', 'http://www.chebiao.net/es.php',
'http://www.chebiao.net/jsk.php', 'http://www.chebiao.net/other.php',
'http://www.chebiao.net/famous.php']
def parse(self, response):
down_url = "http://www.chebiao.net/download.php"
dds = response.xpath("//div[@class='box2']/dl/dd")
for dd in dds:
item = ChebiaoItem()
name = dd.xpath('./a/text()').extract()[0]
url = dd.xpath('./a/@href').extract()[0]
url = down_url + "?" + urlparse(url).query
item['file_name'] = name
item['file_url'] = url
yield item
現在我們已經可以下載全站的圖片了,接下來實作解壓縮檔案,
解壓檔案
由于檔案是 rar 格式,所以需要安裝 unrar 模塊,安裝程序非常簡單,使用 pip install unrar 即可,但是后續出現一些列問題,接下來為大家一一說明,
安裝 unrar 之后,直接使用會出現找不到庫的 BUG,需要下載 unrar library,打開 https://www.rarlab.com/rar_add.htm,找到 UnRAR.dll 下載即可,下載之后的檔案為 UnRARDLL.exe,直接按照到默認路徑,例如我本機為 Windows7 64 位作業系統,安裝路徑為 C:\Program Files (x86)\UnrarDLL,
下面要配置環境變數與檔案名稱,
- 配置
x64目錄到系統環境變數中; - 修改
x64目錄中的UnRaR64.dll和UnRAR64.lib為全小寫字母,

上述內置配置完畢,由于修改了環境變數,為了讓 pycharm 等開發工具加載,需要重啟開發工具,
接下來在 ChebiaoPipeline 類中撰寫如下代碼,重點注意解壓部分相關代碼,
import os
from unrar import rarfile
class ChebiaoPipeline:
def process_item(self, item, spider):
# 獲取檔案完整路徑
path = os.path.join(os.getcwd(), "files", item['file_path'])
# 解壓路徑
extract_path = os.path.join(os.getcwd(), "files")
# 由于檔案設定了【加密檔案名】,所以在加載檔案時,也需要設定密碼
rf = rarfile.RarFile(path, pwd="www.chebiao.net")
# 通過密碼解壓檔案,解壓目錄為當前目錄
rf.extractall(path=extract_path, pwd="www.chebiao.net")
return item
最終運行結果如下所示:

寫在后面
今天是持續寫作的第 249 / 365 天,
期待 關注,點贊、評論、收藏,
更多精彩
《爬蟲 100 例,專欄銷售中,買完就能學會系列專欄》

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339733.html
標籤:python
