当前位置:首页 » python爬虫 » 正文

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

看: 1250次  时间:2020-06-23  分类 : python爬虫

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

标签:scrapy  requests  matplotlib  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!