1、以趣图网为例,首先复制趣图的图片的地址发现图片无法打开,每个图片打开都变成了如下图所示:
出现上述情况的原因则是因为该网站采用了防盗链,为了防止爬虫,可是解决方法还是有的,下面介绍了解决这种情况的方式:
2、spider代码如下:
# -*- coding: utf-8 -*-
import scrapy
from myproject.items import QutuprojectItem
import os
class QutuSpider(scrapy.Spider):
name = 'qutu'
allowed_domains = ['www.gushiking.com']
start_urls = ['http://www.gushiking.com/']
#http://www.gushiking.com/
#http://www.gushiking.com/new/p2.htm
#http://www.gushiking.com/new/p3.htm
url = 'http://www.gushiking.com/new/p{}.htm'
page = 1
#解析网页,提取图片
def parse(self, response):
#找到包括图片信息的p标签
pic_p = response.xpath('//div[@class="pic"]/div[@class="conimg"]')
for op in pic_p:
item = QutuprojectItem()
#获取图片的标题
item["name"] = op.xpath("./p//img/@alt").extract_first()
#获取图片的链接
item["image_url"] = op.xpath("./p//img/@src").extract_first()
yield item
#下载图片
yield scrapy.Request(url=item["image_url"],callback=self.download)
if self.page < 6:
self.page += 1
url = self.url.format(self.page)
yield scrapy.Request(url,callback=self.download)
#下载图片的函数,referer会自动添加
def download(self,response):
#保存图片的地址
dirpath = r'F:\爬虫项目\qutu'
#获取请求的url
image_url = response.url
#获取图片的名字
image_name = os.path.basename(image_url)
#获取图片的路径
image_path = os.path.join(dirpath,image_name)
#下载图片
with open(image_path,'wb') as fp:
fp.write(response.body)