使用scrapy爬取网站上的所有图片

主要的代码逻辑为:

  1. 从start_url开始,下载页面,根据正则表达式提取其中的图片,使用xpath提取<a>标签中的网址链接。
  2. 对于获取的图片链接,先判断之前是否已经爬取过(去重),没有的话,将图片链接拼接成完整的url格式,保存到img.txt中,使用其他的下载软件更快速的下载。(没有直接使用python下载,这样方便调试,检查自己的筛选规则是否正确)
  3. 对于提取到的网址,首先要去重,接着还要判断是否为完整的网址格式,最后发起新的请求:yield Request(url, callback=self.parse)。一般提取到的网址以及当前的页面的网址有以下几种情况:
当前页面网址格式提取的网址格式
http://www.meizu.comhttp://www.meizu.com/index.html
http://www.meizu.com//index.html
http://www.meizu.com/index.htmlindex.html

Spider代码

# -*- coding: utf-8 -*-
import scrapy
import re
from scrapy.http import Request
from ImgInWebsite.items import ImgItem

class ImgSpider(scrapy.Spider):
    name = "ImgSpider"
    allowed_domains = ["www.meizu.com"]
    start_urls = ['http://www.meizu.com/']
    
    URL=[]
    IMG=[]

    def parse(self, response):
        allUrl=response.url
        print allUrl
        # 爬取图片连接
        s=allUrl.split('/')
        root='/'.join(s[0:3])
        # 下面的正则会匹配多个括号
        pattern=re.compile(r'((((https|http):\/\/)|\/)[0-9a-zA-Z\/\.@-_%]*?\.(jpg|png))')
        items=pattern.findall(response.text)
        for item in items:
            img=item[0]
            if img in self.IMG:
                continue
            else:
                self.IMG.append(img)
            
            if img.startswith('/'):
                img=root+img
            elif img.startswith('http') or img.startswith('www'):
                img=img
            else:
                # 当前url加上img
                # 严格还要判断allUrl是不是以'/'结尾
                if allUrl.endswith('/'):
                    img=allUrl+img
                else:
                    img='/'.join(allUrl.split('/')[0:-1])+'/'+img
            imgItem=ImgItem()
            imgItem['img_url']=img
            yield imgItem

        # 爬取继续爬取的网址
        urls=response.xpath('//a/@href').extract()

        for url in urls:
            if url in self.URL:
                continue
            else:
                self.URL.append(url)
            # 组合成完整的url
            if url.startswith('/'):
                url='/'.join(allUrl.split('/')[0:3])+url
            elif url.startswith('http') or url.startswith('www'):
                url=url
            else:
                # 相对路径
                # 还要判断allUrl是不是以'/'结尾
                if allUrl.endswith('/'):
                    url=allUrl+url
                else:
                    url='/'.join(allUrl.split('/')[0:-1])+'/'+url
            
            yield Request(url, callback=self.parse)

项目地址:

https://github.com/wly2014/ImageSpider

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值