python網絡爬蟲之使用scrapy下載文件

前面介紹了ImagesPipeline用於下載圖片,Scrapy還提供了FilesPipeline用與文件下載。和以前的ImagesPipeline同樣,FilesPipeline使用時只須要經過item的一個特殊字段將要下載的文件或圖片的url傳遞給它們,它們便會自動將文件或圖片下載到本地。將下載結果信息存入item的另外一個特殊字段,便於用戶在導出文件中查閱。工做流程以下:html

1 在一個爬蟲裏,你抓取一個項目,把其中圖片的URL放入 file_urls 組內。python

2 項目從爬蟲內返回,進入項目管道。api

3 當項目進入 FilesPipeline,file_urls 組內的URLs將被Scrapy的調度器和下載器(這意味着調度器和下載器的中間件能夠複用)安排下載,當優先級更高,會在其餘頁面被抓取前處理。項目會在這個特定的管道階段保持「locker」的狀態,直到完成文件的下載(或者因爲某些緣由未完成下載)。app

4 當文件下載完後,另外一個字段(files)將被更新到結構中。這個組將包含一個字典列表,其中包括下載文件的信息,好比下載路徑、源抓取地址(從 file_urls 組得到)和圖片的校驗碼(checksum)。 files 列表中的文件順序將和源 file_urls 組保持一致。若是某個圖片下載失敗,將會記錄下錯誤信息,圖片也不會出如今 files 組中。python2.7

下面來看下如何使用:scrapy

第一步:在配置文件settings.py中啓用FilesPipelineide

ITEM_PIPELINES = {
    'scrapy.pipelines.files.FilesPipeline':1,
}

第二步:在配置文件settings.py中設置文件下載路徑函數

FILE_STORE='E:\scrapy_project\file_download\file'

第三步:在item.py中定義file_url和file兩個字段
class FileDownloadItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
file_urls=scrapy.Field()
files=scrapy.Field()

這三步設置後之後,下面就來看下具體的下載了,咱們從matplotlib網站上下載示例代碼。網址是:http://matplotlib.org/examples/index.html網站

接下來來查看網頁結構,以下ui

點擊animate_decay後進入下載頁面。Animate_decay的網頁連接都在<div class=」toctree-wrapper compound」>元素下。

可是像animation Examples這種索引的連接咱們是不須要的

經過這裏咱們能夠首先寫出咱們的網頁獲取連接的方式:

def parse(self,response):
le=LinkExtractor(restrict_xpaths='//*[@id="matplotlib-examples"]/div',deny='/index.html$')
for link in le.extract_links(response):
yield Request(link.url,callback=self.parse_link)

restrict_xpaths設定網頁連接的元素。Deny將上面的目錄連接給屏蔽了。所以獲得的都是具體的文件的下載連接

接下來進入下載頁面,網頁結構圖以下:點擊source_code就能夠下載文件

網頁結構以下

還有另一種既包含代碼連接,又包含圖片連接的

從具體的文件下載連接來看有以下兩種;

http://matplotlib.org/examples/pyplots/whats_new_99_mplot3d.py

http://matplotlib.org/mpl_examples/statistics/boxplot_demo.py

針對這兩種方式獲取對應的連接代碼以下:

def parse_link(self,response):
pattern=re.compile('href=(.*\.py)')
div=response.xpath('/html/body/div[4]/div[1]/div/div')
p=div.xpath('//p')[0].extract()
link=re.findall(pattern,p)[0]
if ('/') in link: #針對包含文件,圖片的下載連接方式生成:http://matplotlib.org/examples/pyplots/whats_new_99_mplot3d.py
href='http://matplotlib.org/'+link.split('/')[2]+'/'+link.split('/')[3]+'/'+link.split('/')[4]
else: #針對只包含文件的下載連接方式生成:http://matplotlib.org/mpl_examples/statistics/boxplot_demo.py
link=link.replace('"','')
scheme=urlparse(response.url).scheme
netloc=urlparse(response.url).netloc
temp=urlparse(response.url).path
path='/'+temp.split('/')[1]+'/'+temp.split('/')[2]+'/'+link
combine=(scheme,netloc,path,'','','')
href=urlunparse(combine)
# print href,os.path.splitext(href)[1]
file=FileDownloadItem()
file['file_urls']=[href]
return file
運行後出現以下的錯誤:提示ValueError: Missing scheme in request url: h。 
2017-11-21 22:29:53 [scrapy] ERROR: Error processing {'file_urls': u'http://matplotlib.org/examples/api/agg_oo.htmlagg_oo.py'}
Traceback (most recent call last):
  File "E:\python2.7.11\lib\site-packages\twisted\internet\defer.py", line 588, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "E:\python2.7.11\lib\site-packages\scrapy\pipelines\media.py", line 44, in process_item
    requests = arg_to_iter(self.get_media_requests(item, info))
  File "E:\python2.7.11\lib\site-packages\scrapy\pipelines\files.py", line 365, in get_media_requests
    return [Request(x) for x in item.get(self.files_urls_field, [])]
  File "E:\python2.7.11\lib\site-packages\scrapy\http\request\__init__.py", line 25, in __init__
    self._set_url(url)
  File "E:\python2.7.11\lib\site-packages\scrapy\http\request\__init__.py", line 57, in _set_url
    raise ValueError('Missing scheme in request url: %s' % self._url)
ValueError: Missing scheme in request url: h
這個錯誤的意思是在url中丟失了scheme. 咱們知道網址的通常結構是:scheme://host:port/path?。 這裏的錯誤意思就是在scheme中沒有找到http而只有一個h. 可是從log記錄的來看,咱們明明是生成了一個完整的網頁呢。爲何會提示找不到呢。緣由就在於下面的這個配置使用的是url列表形式
ITEM_PIPELINES = {
# 'file_download.pipelines.SomePipeline': 300,
'scrapy.pipelines.files.FilesPipeline':1,
}
而咱們的代碼對於item的賦值倒是file['file_urls']=href 字符串的形式,所以若是用列表的方式來提取數據,只有h被提取出來了。所以代碼須要成列表的賦值形式。修改成:file['file_urls']=[href]就能夠了

 

程序運行成功。從保存路徑來看,在download下面新建了一個full文件夾。而後下載的文件都保存在裏面。可是文件名倒是00f4d142b951f072.py這種形式的。這些文件名是由url的散列值的出來的。這種命名方式能夠防止重名的文件相互衝突,可是這種文件名太不直觀了,咱們須要從新來定義下載的文件名名字

在FilesPipeline中,下載文件的函數是file_path。主體代碼以下

Return的值就是文件路徑。從下面看到是文件都是創建在full文件下面

media_guid = hashlib.sha1(to_bytes(url)).hexdigest()  
media_ext = os.path.splitext(url)[1]
return 'full/%s%s' % (media_guid, media_ext)

media_guid獲得的是url的散列值,做爲文件名

media_ext獲得的是文件的後綴名也就是.py

 

下面咱們來從新寫file_path函數用於生成咱們本身的文件名

 

咱們能夠看到有不少網址是下面的形式,widgets是大類。後面的py文件是這個大類下的文件。咱們須要將屬於一個大類的文件歸檔到同一個文件夾下面。

http://matplotlib.org/examples/widgets/span_selector.py http://matplotlib.org/examples/widgets/rectangle_selector.py

http://matplotlib.org/examples/widgets/slider_demo.py

http://matplotlib.org/examples/widgets/radio_buttons.py

http://matplotlib.org/examples/widgets/menu.py

http://matplotlib.org/examples/widgets/multicursor.py

http://matplotlib.org/examples/widgets/lasso_selector_demo.py

 

好比網頁爲http://matplotlib.org/examples/widgets/span_selector.py

urlparse(request.url).path 獲得的結果是examples/widgets/span_selector.py
dirname(path)獲得的結果是examples/widgets
basename(dirname(path))獲得的結果是widgets
join(basename(dirname(str)),basename(str))獲得的結果是widgets\ span_selector.py
重寫pipeline.py以下:
from scrapy.pipelines.files import FilesPipeline
from urlparse import urlparse
from os.path import basename,dirname,join
class FileDownloadPipeline(FilesPipeline):
def file_path(self, request, response=None, info=None):
path=urlparse(request.url).path
temp=join(basename(dirname(path)),basename(path))
return '%s/%s' % (basename(dirname(path)), basename(path))
運行程序發現生成的文件名仍是散列值的。緣由在於在以前的setting.py中,咱們設置的是'scrapy.pipelines.files.FilesPipeline':1
這將會直接採用FilesPipeline。如今咱們重寫了FilesPipeline就須要更改這個設置,改成FileDownloadPipeline
ITEM_PIPELINES = {
# 'file_download.pipelines.SomePipeline': 300,
# 'scrapy.pipelines.files.FilesPipeline':1,
'file_download.pipelines.FileDownloadPipeline':1,
}
再次運行,獲得以下的結果:同一類的文件都被歸類到了同一個文件夾下面。

且文件名採用的是更直觀的方式。這樣比散列值的文件名看起來直觀多了

matplotlib文件打包的下載連接以下,有須要的能夠下載

https://files.cnblogs.com/files/zhanghongfeng/matplotlib.rar

scrapy工程代碼以下:

https://files.cnblogs.com/files/zhanghongfeng/file_download.rar

相關文章
相關標籤/搜索