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