欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-03-08 11:40:15|栏目: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流程控制语句的深入讲解

栏    目:Python代码

下一篇:Python中的字符串类型基本知识学习教程

本文标题:Python Scrapy图片爬取原理及代码实例

本文地址:http://www.codeinn.net/misctech/76810.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有