网络编程
位置:首页>> 网络编程>> Python编程>> Python Scrapy图片爬取原理及代码实例

Python Scrapy图片爬取原理及代码实例

作者:Hedger_Lee  发布时间:2022-04-29 05:51:06 

标签: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

来源:https://www.cnblogs.com/Hedger-Lee/p/13072581.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com