前一篇写了基础的爬虫,这篇我们就来爬图片保存下来。环境如上一篇
Step1
首先还是实体类写好我们需要的字段 注释中ImagesPipeline
后面会解释
from scrapy import Item, Fieldclass PaimgItem(Item): # 这两个字段 image_urls images是ImagesPipeline存放需要的 image_urls = Field() images = Field() name = Field()复制代码
Step2
项目结构不变,依然首先来写我们的Spider
import scrapyfrom scrapy.spiders import CrawlSpiderfrom PaImg.items import PaimgItemclass MeizituSpider(CrawlSpider): name = "meizitu" host = 'http://www.meizitu.com/' start_urls = ['http://www.meizitu.com/a/sexy.html'] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', } def parse(self, response): nextPage = response.xpath(u'//div[@id="wp_page_numbers"]//a[text()="下一页"]/@href').extract_first() nextPage = self.host + nextPage for p in response.xpath('//li[@class="wp-item"]//a/@href').extract(): # scrapy.Request再次请求获取详情html由parse_item解析 yield scrapy.Request(p, callback=self.parse_item) yield scrapy.Request(nextPage, callback=self.parse) def parse_item(self, response): item = PaimgItem() # 详情中的图片列表 item['image_urls'] = response.xpath("//div[@id='picture']//img/@src").extract() item['name'] = response.xpath("//div[@id='picture']//img/@alt").extract()[0].split(u',')[0] return item复制代码
上一篇如果你认真看了写了,这一点代码相信你一眼就看懂了。如果不懂先看一下上一篇吧
Step3
上面我们将详情页的图片列表地址存储保存了下来。我们需要一个专门下载每张图片的类。 也就是Step1中提到的ImagesPipeline
。它是用来处理下载图片的一个Pipeline
关于Pipline可以查看。我们创建一个PaimgPipeline
类继承自ImagesPipeline
class PaimgPipeline(ImagesPipeline):复制代码
我们需要复写四个方法:get_media_requests(进行图片下载请求处理) item_completed(图片下载完成的通知) file_path(下载原始图片的保存路径) thumb_path(缩略图保存路径)
完整代码:
headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', "Referer": "https://www.meizitu.com/", # 加入referer 为下载的域名网站}class PaimgPipeline(ImagesPipeline): # 在工作流程中可以看到,管道会得到图片的URL并从项目中下载。 # # 为了这么做,你需要重写 get_media_requests() 方法,并对各个图片URL返回一个Request: def get_media_requests(self, item, info): for image_url in item['image_urls']: # 这里把item传过去,因为后面需要用item里面的name作为文件名 yield Request(image_url, meta={ 'item': item}, headers=headers) def item_completed(self, results, item, info): image_paths = [x['path'] for ok, x in results if ok] if not image_paths: raise DropItem("Item contains no images") return item def file_path(self, request, response=None, info=None): item = request.meta['item'] image_guid = request.url.split('/')[-1] # 倒数第一个元素 filenames = "full/%s/%s" % (item['name'], image_guid) # print(filename) return filenames def thumb_path(self, request, thumb_id, response=None, info=None): item = request.meta['item'] image_guid = request.url.split('/')[-1] # 倒数第一个元素 # thumb_id就是setting文件中定义的big small filenames = "thumbil/%s/%s/%s" % (thumb_id, item['name'], image_guid) return filenames复制代码
Step4
编写随机的UserAgent
和IP代理
import randomfrom scrapy.downloadermiddlewares.useragent import UserAgentMiddleware'''这个类主要用于产生随机UserAgent'''class RandomUserAgent(UserAgentMiddleware): def __init__(self, agents): self.agents = agents @classmethod def from_crawler(cls, crawler): return cls(crawler.settings.getlist('USER_AGENTS')) # 返回的是本类的实例cls ==RandomUserAgent def process_request(self, request, spider): request.headers.setdefault('User-Agent', random.choice(self.agents))复制代码
import randomfrom PaImg.settings import IPPOOLclass ProxiesMiddleware(object): def __init__(self, ip=''): self.ip = ip def process_request(self, request, spider): thisip = random.choice(IPPOOL) print("this is ip:" + thisip["ipaddr"]) request.meta["proxy"] = "http://" + thisip["ipaddr"]复制代码
Step5
下来我们就需要配置一下settings.py
了。
- 首先我们先把刚刚写的
PaimgPipeline
配置到settings中
ITEM_PIPELINES = { 'PaImg.pipelines.PaimgPipeline': 300,}复制代码
- 设置上面编写的
RandomUserAgent
及ProxiesMiddleware
DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'PaImg.RandomUserAgent.RandomUserAgent': 100, # 代理IP可能会失效 需要重新ping代理ip地址 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware' : None, 'PaImg.ProxiesMiddleware.ProxiesMiddleware' : 100}复制代码
- 设置USER_AGENTS,也就是上面我们自己编写
RandomUserAgent
需要的数据
USER_AGENTS = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)", "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1", "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11", "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"]复制代码
- 设置IPPOOL,也就是上面我们自己编写
ProxiesMiddleware
需要的数据( 代理IP可能会失效 需要重新ping代理ip地址)
IPPOOL=[ { "ipaddr":"211.142.141.210:8998"}, { "ipaddr":"58.19.15.218:808"}, { "ipaddr":"117.90.1.141:9000"}, { "ipaddr":"125.117.115.180:9000"}, { "ipaddr":"211.142.141.210:8998"}, { "ipaddr":"163.125.251.242:8118"}]复制代码
- 设置上面略缩图的大小,有两种方式:
IMAGES_THUMBS = { 'small': (50, 50), 'big': (270, 270),}复制代码
- 设置图片(宽最小与高最小)过滤。以防止我们会下载一些广告图或其他无用图
IMAGES_MIN_HEIGHT = 110IMAGES_MIN_WIDTH = 110复制代码
- 设置本地保存路径
IMAGES_STORE = '/Users/cuiyang/Pictures/meizitu'复制代码
- 还有我们的延迟下载
DOWNLOAD_DELAY = 2复制代码
基本上这些就已经够了,我们还可以再优化一下配置,也是比较通用的一些配置
Tip
- 减少超时时间以提高爬取速度
DOWNLOAD_TIMEOUT = 15复制代码
- 不对失败的HTTP请求进行重试
RETRY_ENABLED = False复制代码
- 禁用cookie
COOKIES_ENABLED = False 复制代码
- 通用爬取经常抓取大量的 “index” 页面; AjaxCrawlMiddleware能帮助您正确地爬取。 由于有些性能问题,且对于特定爬虫没有什么意义,该中间默认关闭。
AJAXCRAWL_ENABLED = False复制代码
最后附上源码地址: