scrapy爬取图片

1、需要掌握的知识点:
  • scrapy爬虫框架
  • urllib2库
2、urllib2库介绍

urllib2是获取URL的一个组件,提供一些复杂的接口用于处理: 基本认证,重定向,Cookies等。urllib2支持许多的“URL schemes”(由URL中的“:”之前的字符串确定 - 例如“FTP”的URL方案如“ftp://python.org/”),且他还支持其相关的网络协议(如FTP,HTTP)。我们则重点关注HTTP。

3、常用方法

urllib2.urlopen()打开一个url返回一个对象
urllib2.request()打开一个url并返回一个request对象,这个对象可以使用urlopen打开,后续方法可以进行read。
4、开始编码,爬取图片
  • 在items.py定义模型

class DouspiderItem(scrapy.Item):
    # define the fields for your item here like:
    img = scrapy.Field() #电影图片

  • 获取图片链接
def parse(self,response):
		for info in response.xpath("//div[@class='item']"):
			item = DouspiderItem()
			item['img'] = info.xpath("div[@class='pic']/a/img/@src").extract()
			yield item
			next_page = response.xpath("//span[@class='next']/a/@href") 
		#获取下一页链接	
		if next_page: 
			url = response.urljoin(next_page[0].extract()) 
			yield scrapy.Request(url, self.parse)
  • 保存图片
def process_item(self, item, spider):
         tmp_file_path=self.dir_path+spider.name
         tmp_file_path += '/'
         for image_url in item['img']:
            file_path=''
            sfile=''
            list_name = image_url.split('/')
            file_name = list_name[len(list_name)-1]
            file_path = tmp_file_path+(file_name)
            if os.path.exists(file_path):
                continue
            with open(file_path,'wb') as f:
                conn = urllib2.urlopen(image_url)
                f.write(conn.read())
            f.close()
         return item


5、运行结果
运行命令:scrapy crawl DouSpide

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值