前言

可能在大家学习爬虫的过程中已经学会了如何去下载文件和图片的,无非就是传递一个URL地址然后下载即可,那么在Scrapy这个框架中,又是如何下载文件和图片的呢?

在Scrapy中,存在两个处理管道,分别是FilesPipeline,ImagesPipeline,一个用来下载文件,一个用来下载图片,下面用两个实例来说明这两个管道的用法

FilesPipeline

下载下图网站的代码文件

items.py

1
2
3
4
5
6
7
8
9
import scrapy

class DownFilesItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#pass
#file_urls用来存放要下载的文件url地址
file_urls = scrapy.Field()
files = scrapy.Field()

settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
BOT_NAME = 'Down_Files'

SPIDER_MODULES = ['Down_Files.spiders']
NEWSPIDER_MODULE = 'Down_Files.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Down_Files (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

ITEM_PIPELINES = {
#'Down_Files.pipelines.DownFilesPipeline': 300,
#自动下载文件,本来是FilesPipeline,为了改变下载文件的文件名,重写了FilesPipeline
#'scrapy.pipelines.files.FilesPipeline':1,
'Down_Files.pipelines.DownFilesPipeline':1,
}
#下载的文件存放路径
FILES_STORE='Down_Files'

pipelines.py

1
2
3
4
5
6
7
8
9
10
from scrapy.pipelines.files import FilesPipeline
from urllib.parse import urlparse
from os.path import basename,dirname,join

#改变下载的文件名
class DownFilesPipeline(FilesPipeline):
#Scrapy源代码用这个方法来命名,return(目录名,文件名),我们改变返回值的目录名和文件名即可
def file_path(self,request,response=None,info=None):
path = urlparse(request.url).path
return join(basename(dirname(path)),basename(path))

Down_Files.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- coding: utf-8 -*-
import scrapy

from scrapy.linkextractors import LinkExtractor
from Down_Files.items import DownFilesItem

class DownFileSpider(scrapy.Spider):
name = 'Down_File'
allowed_domains = ['matplotlib.org']
start_urls = ['http://matplotlib.org/examples/index.html']

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

def parse_files(self, response):
href = response.xpath('//div[@class="body"]/div/p/a/@href').extract_first()
url = response.urljoin(href)
item = DownFilesItem()
item['file_urls'] = [url]
return item

成果图如下

ImagesPipeline

下载So_Image的图片

items.py

1
2
3
4
5
6
7
import scrapy

class DownSoImageItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
#跟下载文件一样,存放图片的url地址
image_urls = scrapy.Field()

settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
BOT_NAME = 'Down_So_Image'

SPIDER_MODULES = ['Down_So_Image.spiders']
NEWSPIDER_MODULE = 'Down_So_Image.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Down_So_Image (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

DEFAULT_REQUEST_HEADERS = {
#'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#'Accept-Language': 'en',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1',
}
ITEM_PIPELINES = {
#'Down_So_Image.pipelines.DownSoImagePipeline': 300,
'scrapy.pipelines.images.ImagesPipeline':1,
}

IMAGES_STORE = 'Down_Images'

Down_Images.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import scrapy

from scrapy.linkextractors import LinkExtractor
from Down_Files.items import DownFilesItem

class DownFileSpider(scrapy.Spider):
name = 'Down_File'
allowed_domains = ['matplotlib.org']
start_urls = ['http://matplotlib.org/examples/index.html']

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

def parse_files(self, response):
href = response.xpath('//div[@class="body"]/div/p/a/@href').extract_first()
url = response.urljoin(href)
item = DownFilesItem()
item['file_urls'] = [url]
return item

成果图片如下