FilesPipline ---是scrapy爬蟲中用到的用於下載文件的一個方法
文章所提供的代碼都是自己學習的代碼的路上經過測試已經成功的代碼
通過css樣式提取文件的地址與ImagesPipeline不同,在css樣式裡邊直接存在文件的地址,那麼在css樣式裡邊獲取也是可以的,上一篇中的在json文件中,是可以直接獲取到每張圖片的地址,因此僅僅是文件的地址顯示方式不一樣,採用的獲取方式不同,並不是文件就必須採用css樣式獲取。
- cmd命令創建project
按照下邊的紅色標記進行操作。最終創建的文件夾在document裡邊可以顯示。
- 打開編輯器
首先修改setting.py文件
修改ROBOTSTXT_OBEY (如果不修改這個,就會出現程序運行成功,但是沒有文件下來保存)
<code>ROBOTSTXT_OBEY = True/<code>
- 啟用ImagesPipline
<code>ITEM_PIPELINES = {
# 'matplotlib_examples.pipelines.MatplotlibExamplesPipeline': 300,
'scrapy.pipelines.files.FilesPipeline':1,
'matplotlib_examples.pipelines.MatplotlibExamplesPipeline':1
}
FILES_STORE='examples_src'/<code>
- 設定Item
<code>import scrapy
class MatplotlibExamplesItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
file_urls=scrapy.Field()
files=scrapy.Field()/<code>
- 設定pip文件保存的格式和名字
<code>from scrapy.pipelines.files import FilesPipeline
from urllib.parse import urlparse
from os.path import basename,dirname,join
class MatplotlibExamplesPipeline(FilesPipeline):
def file_path(self,request,response=None,info=None):
path=urlparse(request.url).path
return join(basename(dirname(path)),basename(path))
/<code>
- 實現ImageSpider
<code>import scrapy
from scrapy.linkextractors import LinkExtractor
from ..items import MatplotlibExamplesItem
class ExamplesSpider(scrapy.Spider):
name = 'examples'
allowed_domains = ['matplotlib.org']
start_urls = ['http://matplotlib.org/examples/index.html']
#第一層,在第一層的分類上獲取所有的文件列表
def parse(self, response):
#LinkExtractor是用於多個數據的列表
le=LinkExtractor(restrict_css='div.toctree-wrapper.compound',deny='/index.html$')
print(len(le.extract_links(response)))
for link in le.extract_links(response):
yield scrapy.Request(link.url,callback=self.parse_example)
def parse_example(self,response):
#response裡邊帶有的css方法是獲取到單個列表
href=response.css('a.reference.external::attr(href)').extract_first()
#獲取的列表
url=response.urljoin(href)
example=MatplotlibExamplesItem()
example['file_urls']=[url]
return example
/<code>
- 運行
<code>scrapy crawl examples/<code>
-----有疑問可以私信聯繫
閱讀更多 國家301實驗室 的文章