###一、scrapy图片爬虫构建思路
1.分析网站
2.选择爬取方式与策略
3.创建爬虫项目 → 定义items.py
4.编写爬虫文件
5.编写pipelines与setting
6.调试
二、千图网难点(http://www.58pic.com/)
1.要爬取全站的图片
2.要爬取高清的图片------找出高清地址即可
3.要有相应的反爬虫机制------如模拟浏览器,不记录cookie等,只要相应注释去掉即可COOKIES_ENABLED = False
三、散点知识
1.from scrapy.http import Request 是回调函数用Request(url=…,callback=…)
2.xpath的//表示提取所有符合的节点
代码:
items.py
import scrapy
class QiantuwangItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
url = scrapy.Field()
title = scrapy.Field()
middlewares.py
from scrapy import signals
class QiantuwangSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
import urllib
import random
class QiantuwangPipeline(object):
def process_item(self, item, spider):
try:
title = item['title'][0].encode('gbk')
file = "E:/tupian/" + str(title) + str(int(random.random() * 10000)) + ".jpg"
urllib.urlretrieve(item['url'][0], filename=file)
except Exception, e:
print e
pass
return item