最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python Scrapy图片爬取原理及代码实例
时间:2020-06-12 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Python Scrapy图片爬取原理及代码实例,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
1.在爬虫文件中只需要解析提取出图片地址,然后将地址提交给管道
在管道文件对图片进行下载和持久化存储
class ImgSpider(scrapy.Spider): name = 'img' # allowed_domains = ['www.xxx.com'] start_urls = ['http://www.521609.com/daxuemeinv/'] url = 'http://www.521609.com/daxuemeinv/list8%d.html' pageNum = 1 def parse(self, response): li_list = response.xpath('//*[@id="content"]/div[2]/div[2]/ul/li') for li in li_list: img_src = 'http://www.521609.com'+li.xpath('./a[1]/img/@src').extract_first() item = ImgproItem() item['src'] = img_src yield item
2.配置文件修改
配置文件要增加IMAGES_STORE = './imgsLib'表明图片存放的路径
3.管道类的修改
原本管道类继承的object,处理item对象使用时process_item方法,该方法不能发送请求,要想对图片地址发送请求,需要继承ImagesPipeline类,然后重写该类中的三个方法:get_media_requests,file_path,item_completed
from scrapy.pipelines.images import ImagesPipeline import scrapy class ImgproPipeline(ImagesPipeline): #对某一个媒体资源进行请求发送 #item就是接收到的spider提交过来的item def get_media_requests(self, item, info): yield scrapy.Request(item['src']) #制定媒体数据存储的名称 def file_path(self, request, response=None, info=None): name = request.url.split('/')[-1] print('正在下载:',name) return name #将item传递给下一个即将给执行的管道类 def item_completed(self, results, item, info): return item
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27