欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python爬蟲框架scrapy實現(xiàn)的文件下載功能示例

 更新時間:2018年08月04日 08:56:04   作者:Charles.L  
這篇文章主要介紹了Python爬蟲框架scrapy實現(xiàn)的文件下載功能,結(jié)合實例形式分析了scrapy框架進行文件下載的具體操作步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了Python爬蟲框架scrapy實現(xiàn)的文件下載功能。分享給大家供大家參考,具體如下:

我們在寫普通腳本的時候,從一個網(wǎng)站拿到一個文件的下載url,然后下載,直接將數(shù)據(jù)寫入文件或者保存下來,但是這個需要我們自己一點一點的寫出來,而且反復(fù)利用率并不高,為了不重復(fù)造輪子,scrapy提供很流暢的下載文件方式,只需要隨便寫寫便可用了。

mat.py文件

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractor import LinkExtractor
from weidashang.items import matplotlib
class MatSpider(scrapy.Spider):
  name = "mat"
  allowed_domains = ["matplotlib.org"]
  start_urls = ['https://matplotlib.org/examples']
  def parse(self, response):
       #抓取每個腳本文件的訪問頁面,拿到后下載
    link = LinkExtractor(restrict_css='div.toctree-wrapper.compound li.toctree-l2')
    for link in link.extract_links(response):
      yield scrapy.Request(url=link.url,callback=self.example)
  def example(self,response):
      #進入每個腳本的頁面,抓取源碼文件按鈕,并和base_url結(jié)合起來形成一個完整的url
    href = response.css('a.reference.external::attr(href)').extract_first()
    url = response.urljoin(href)
    example = matplotlib()
    example['file_urls'] = [url]
    return example

pipelines.py

class MyFilePlipeline(FilesPipeline):
  def file_path(self, request, response=None, info=None):
    path = urlparse(request.url).path
    return join(basename(dirname(path)),basename(path))

settings.py

ITEM_PIPELINES = {
  'weidashang.pipelines.MyFilePlipeline': 1,
}
FILES_STORE = 'examples_src'

items.py

class matplotlib(Item):
  file_urls = Field()
  files = Field()

run.py

from scrapy.cmdline import execute
execute(['scrapy', 'crawl', 'mat','-o','example.json'])

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

最新評論