scrapy为下载 item上包含的文件(比如在爬取到产品时,同时也想保存对应的图片)提供了一个可重用的item pipelines。这些pipeline 有些共同的方法和结构(我们称之为media pipeline)。一般来说你会使用Files Pipeline或者images pipelines。
为什么要选择scrapy内置的下载文件的方法
1:避免重新下载最近已经下载过的数据
2:可以方便的指定文件存储的路径
3:可以将下载的图片转换成通用的格式。如:png,jpg
4:可以方便的生成缩略图
5:可以方便的检测图片的宽和高,确保他们满足最小限制
6:异步下载,效率非常高
(crawler) F:\WWWROOT\crawler>scrapy startproject bmw
(crawler) F:\WWWROOT\crawler>scrapy genspider bmw5 "car.autohome.com.cn"
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 1
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 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
}
ITEM_PIPELINES = {
'bmw.pipelines.BmwPipeline': 300,
}
from scrapy import cmdline
cmdline.execute("scrapy crawl bmw5".split())
启动文件用来代替命令行启动,文件放在项目根目录下
import scrapy
from xspider.items import XspiderItem
class ScandalSpider(scrapy.Spider):
name = 'bmw'
allowed_domains = ['car.autohome.com.cn']
start_urls = ['https://car.autohome.com.cn/pic/series/202.html']
def parse(self, response):
uiboxs = response.xpath('//div[@class="uibox"]')[1:]
for uibox in uiboxs:
category = uibox.xpath('.//div[@class="uibox-title"]/a/text()').get()
urls = uibox.xpath('.//ul/li/a/img/@src').getall()
urls = list(map(lambda url: response.urljoin(url), urls))
item = XspiderItem(category = category, urls = urls)
yield item
import scrapy
class XspiderItem(scrapy.Item):
category = scrapy.Field()
urls = scrapy.Field()
import os
from urllib import request
class AutohomePipeline:
def __init__(self):
self.image_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')
self.create_dir(self.image_path)
def create_dir(self, dir_path):
if not os.path.exists(dir_path): os.mkdir(dir_path)
def process_item(self, item, spider):
category = item.get('category')
urls = item.get('urls')
category_path = os.path.join(self.image_path, category)
self.create_dir(category_path)
for url in urls:
image_name = url.split('_')[-1]
request.urlretrieve(url, os.path.join(category_path, image_name))
return item
Python3 OS模块使用见:
https://blog.csdn.net/pcn01/article/details/99182643
使用Files Pipeline下载文件,按照以下步骤完成:
使用images pipeline下载文件步骤:
import os
ITEM_PIPELINES = {
# 'bmw.pipelines.BmwPipeline': 300,
'scrapy.pipelines.images.ImagesPipeline': 1 # 使用scrapy内置的ImagesPipeline
}
# 配置文件的下载路径
IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')
import scrapy
class BmwItem(scrapy.Item):
category = scrapy.Field()
image_urls = scrapy.Field()
images = scrapy.Field()
由于字段修改了,在爬取数据文件中,只需要修改下字段名即可
class BmwSpider(scrapy.Spider):
name = 'bmw'
allowed_domains = ['car.autohome.com.cn']
start_urls = ['https://car.autohome.com.cn/pic/series/4472.html']
def parse(self, response):
uiboxs = response.xpath('//div[@class="uibox"]')[1:]
for uibox in uiboxs:
category = uibox.xpath('.//div[@class="uibox-title"]/a/text()').get()
url_list = uibox.xpath('.//ul/li/a/img/@src').getall()
# urls = ['https:' + url for url in url_list]
urls = list(map(lambda url: response.urljoin(url), url_list))
item = AutohomeItem(category = category, image_urls = urls) # 修改这里的urls为image_urls
yield item
修改完后即可运行程序,下载图片(异步下载)。
下载的图片都保存在images/full/目录下,为什么了多了full这个目录,查看下源码:
由于scrapy默认的Images Pipeline目录结构不是我们想要的,我们希望图片按照目标站的分类进行创建目录结构,所以必须得重写保存路径的代码
首先修改下settings配置文件:
ITEM_PIPELINES = {
# 'bmw.pipelines.BmwPipeline': 300,
# 'scrapy.pipelines.images.ImagesPipeline': 1
'bmw.pipelines.BmwImagesPipeline': 1 # 自定义的BmwImagesPipeline类
}
在pipelines.py文件实现自定义的BmwImagesPipeline类:
import os
from urllib import request
from scrapy.pipelines.images import ImagesPipeline
from bmw import settings
class BmwPipeline(object):
# 由于使用了自定义的类,该方法不会被执行
def __init__(self):
self.path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images')
if not os.path.exists(self.path):
os.mkdir(self.path)
def process_item(self, item, spider):
category = item['category']
urls = item['urls']
category_path = os.path.join(self.path, category)
if not os.path.exists(category_path):
os.mkdir(category_path)
for url in urls:
image_name = url.split('_')[-1]
request.urlretrieve(url, os.path.join(category_path, image_name))
return item
class BmwImagesPipeline(ImagesPipeline):
# 重写父类的下面两个方法
def get_media_requests(self, item, info):
# 该方法在发送下载请求前调用,其实这个方法本身就是去发送下载请求的
# 因为file_path中并没有item对象,所以使用该方法将item动态绑定到request对象上
request_objs = super(BmwImagesPipeline, self).get_media_requests(item, info)
for request_obj in request_objs:
request_obj.item = item
return request_objs
def file_path(self, request, response = None, info = None):
# 该方法是在图片将要被存储的时候调用,来获取这个图片存储路径
path = super(BmwImagesPipeline, self).file_path(request, response, info)
category = request.item.get('category')
images_store = settings.IMAGES_STORE
category_path = os.path.join(images_store, category)
if not os.path.exists(category_path):
os.mkdir(category_path)
image_name = path.replace('full/', '')
image_path = os.path.join(category_path, image_name)
return image_path