Scrapy爬取图片: raise ValueError('Missing scheme in request url: %s' % self._url)

13 篇文章 0 订阅
5 篇文章 0 订阅

Scrapy爬取图片也很简单,有以下几点:
1.settings.py

BOT_NAME = 'tianmaoimg'

SPIDER_MODULES = ['tianmaoimg.spiders']
NEWSPIDER_MODULE = 'tianmaoimg.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'tianmaoimg (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {'scrapy.pipelines.images.ImagesPipeline': 1}

IMAGES_URLS_FIELD='file_urls'
IMAGES_STORE = '/path/to/valid/images'

2.items.py

import scrapy


class TianmaoimgItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    #图片链接
    file_urls=scrapy.Field()

3.spider: getImgs.py 部分代码

   #图片链接
            try:
                file_urls=div.xpath('div[@class="productImg-wrap"]/a[@class="productImg"]/img/@src|'
                                   'div[@class="productImg-wrap"]/a[@class="productImg"]/img/@data-ks-lazyload').extract()
                #print file_urls[0]

####有错误
                item['file_urls']=file_urls[0] if 'http:' in file_urls[0] else ('http:'+file_urls[0])

            except Exception,e:
                print('error',e)

###########设置断点 ,跟踪代码的工具pdb,显示错误路径
                import pdb;pdb.set_trace()

            yield scrapy.Request(url=item['link_url'],meta={'item':item},callback=self.parse_item,dont_filter=True)

竟然报了一个很奇葩的错误
这里写图片描述

解决错误:
找了半天才从简书中知道,究其根源:
:在settings.py存储图片,其ITEM_PIPELINES = {‘scrapy.pipelines.images.ImagesPipeline’: 1}用到的是图片的url列表,而在Spider类中返回的是一个url字符串,所以ITEM_PIPELINES参数在执行循环获取url列表时,出现了只获取到了字符串的h,也就是上述的错误

所以改正:

item['file_urls']=[file_urls[0] if 'http:' in file_urls[0] else ('http:'+file_urls[0])]

ok

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值