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
相关推荐
weiiron 2020-08-17
生物信息学 2020-06-22
adamlovejw 2020-06-11
bcbeer 2020-05-02
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
digwtx 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15