一、爬取昵图网
第一步:
1、新建项目
scrapy startproject nituwang
2、新建爬虫
scrapy genspider nituwang_spider nipic.com
3、更改设置
……
第二步:
1、爬虫启动文件
from scrapy import cmdline
cmdline.execute("scrapy crawl --nolog nituwang_spider".split()) #启动爬虫,无日志
第三步:
1、写items.py文件:
用来存放爬虫爬取下来数据的模型,类似Django的models,不过这个没有整型、字符……之分。
items.py
import scrapy
class NituwangItem(scrapy.Item):
big_image_url = scrapy.Field() #存放高清大图
title = scrapy.Field() #图的名字
第四步:
1、写爬虫:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from urllib import parse
import re
from ..items import NituwangItem
class NituwangSpiderSpider(scrapy.Spider):
name = 'nituwang_spider'
allowed_domains = ['nipic.com']
start_urls = ['http://www.nipic.com/photo/lvyou/ziran/index.html', ] # 爬虫开始url
def parse(self, response):
image_urls = response.xpath('//li[contains(@class,"new-works-box")]/a/@href').getall()
# 图片详情页
for image_url in image_urls:
# 发起请求,->图片详情页,解析图片详情页。
yield Request(parse.urljoin(response.url, image_url), callback=self.parse_detail)
# 获取总页数。因为这个网址的最后一页的下一页是第一页
end_link = response.xpath('//a[@class="bg-png24 page-btn"][2]/@href').get()
res = re.match('.*?(\d{1,10})', end_link)
end_num = res.group(1)
for i in range(1, int(end_num)):
url = 'http://www.nipic.com/photo/lvyou/ziran/index.html?page={}'.format(i)
# 请求下一页,继续解析
yield Request(url, callback=self.parse)
# 图片详情页,获取高清大图
def parse_detail(self, response):
item = NituwangItem()
big_image_url = response.xpath('//img[@id="J_worksImg"]/@src').get() # 大图链接
item['big_image_url'] = [big_image_url] # 传递列表,下载图片需要使用列表
item['title'] = response.xpath('//img[@id="J_worksImg"]/@alt').get() #图片名
return item
第五步:
1、进入pipelines,对爬取下来的数据进行操作。
get_media_requests----->file_path--->item_completed
from scrapy.pipelines.images import ImagesPipeline
from scrapy.http import Request
import random
class MyImagePipeline(ImagesPipeline):
def get_media_requests(self, item, info):
'''
是在发送下载请求之前调用
去发送下载图片的请求
'''
#meta用来传递信息,在file_path中没有item信息。
for image_url in item['big_image_url']:
yield Request(image_url, meta={'title': item['title']})
def item_completed(self, results, item, info):
print('******the results is********:', results) #也可以在这个方法中更改文件名,因为在file_path存储完成后,item_completed里有个results参数,results参数保存了图片下载的相关信息
return item
def file_path(self, request, response=None, info=None):
'''
这个方法是在图片将要被存储的时候调用,来获取这个图片存储的路径
:param request:
:param response:
:param info:
:return: 存储路径
'''
a = 'abcdefghijklmnopqrstuvwxyz1234567890'
b = ''.join(random.sample(a, 10))
title = request.meta['title'].strip() + b # 因为会有重复的名字,所以从随机提取几个字符
path = '风景/%s.jpg' % (title)
return path
第六步:
1、在settings.py文件中设置
……
ITEM_PIPELINES = {
# 'nituwang.pipelines.NituwangPipeline': 300,
# 'scrapy.pipelines.images.ImagesPipeline': 1,
'nituwang.pipelines.MyImagePipeline': 1,
}
path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(path, 'images')
IMAGES_STORE = path # 存储的路径,不写绝对路径,在别的系统运行时,需要重新设定。
IMAGES_URLS_FIELD = 'big_image_url' # 要下载的字段,使用哪个url
……