当有CONCURRENT_REQUESTS,没有DOWNLOAD_DELAY 时,服务器会在同一时间收到大量的请求。
当有CONCURRENT_REQUESTS,有DOWNLOAD_DELAY 时,服务器不会在同一时间收到大量的请求。
两种方法能够使 requests 不被过滤:
1. 在 allowed_domains
中加入 url
2. 在 scrapy.Request() 函数中将参数 dont_filter=True
设置为 True
去掉重复过滤器无望的情况下, 可以先在Request的初始化函数中, 传入dont_filter=True.
理解:
第一个作用:
(allowed_domains中限制允许发送请求的url,假如你发送的请求被allowed限制,你又想发送请求,在request请求中设置参数dont_filter=True)
第二个作用:
重复抓取一个页面的方法
# scrapy默认会过滤重复网页,发起Request添加dont_filter=True,则可以重复请求
# 使用的时候要注意, 不要进入死循环
文档详解:VVVV
dont_filter( boolean) - 表示调度程序不应过滤此请求。当您想要多次执行相同的请求时,可以使用此选项来忽略重复过滤器。小心使用它,否则您将进入爬行循环。默认为False。
使用中遇到的一些问题
- 一个爬虫项目中,是否支持多个Item?
- 在一个页面抓取多个Item?不同的Item如何存储?
- 爬虫进入下一级网页?
- 在爬虫中携带自定义数据?
- 重复抓取一个页面的方法?
- 分别指定每个爬虫的设置?
- 防止爬虫被ban?
针对以上问题,下面给出具体的代码示例
- 定义可以定义多个Item
# myspider/items.py
import scrapy
class Item1(scrapy.Item):
url = scrapy.Field()
name = scrapy.Field()
class Item2(scrapy.Item):
url = scrapy.Field()
job_id = scrapy.Field()
job_title = scrapy.Field()
- 具体的爬虫脚本
# myspider/spiders/myspider.py
class Spider1(CrawlSpider):
# 爬虫的名字
name = "spider1"
# 要抓取的网页限制
allowed_domains = ["mysite.com"]
# 指定开始抓取的url
start_urls = [
"http://mysite.com/",
"http://mysite2.com/",
]
# parse方法为抓取入口
# 抓取 start_urls 中的网址
def parse(self, response):
sel = Selector(response)
# 在一个页面抓取多个Item
# 在分析网页过程中,通过 yield item ,可以生成多个item
item = new Item1()
item['url'] = response.url
item['name'] = sel.xpath('').extract()
yield item
item2 = new Item2()
item2['url'] = response.url
item2['job_id'] = sel.xpath('//h2[1]/a/@href').extract()
item2['job_title'] = sel.xpath('//div[@class="box"]/a/text()').extract()
# 如何使爬虫进入下一级网页?
# 使用 yield Request()方法
yield Request(url, callback=self.parse1)
# 在爬虫中携带自定义数据
# 添加meta参数
yield Request(url,
meta={'referer' : url, 'job_id': item2['job_id']},
callback=self.parse2)
# 重复抓取一个页面的方法
# scrapy默认会过滤重复网页,发起Request添加dont_filter=True,则可以重复请求
# 使用的时候要注意, 不要进入死循环
if some_condition:
yield Request(url, callback=self.parse, dont_filter=True)
def parse1(self, response):
sel = Selector(response)
def parse2(self, response):
sel = Selector(response)
# 使用 response.meta 来访问
print response.meta['job_id']
- 接第一个问题,多个Item,如何存储?
# 在pipelines中的脚本示例
# myspider/pipelines.py
class MyPipeline(object):
def __init__(self):
print("MyPipeline init")
def open_spider(self, spider):
print("Pipeline opend")
def close_spider(self, spider):
print("MyPipeline closed")
def process_item(self, item, spider):
print 'process_item'
if isinstance(item, Item1):
# item1的存储逻辑
print item
if isinstance(item, Item2):
# item2的存储逻辑
print item
# myspider/settings.py
# 使用MyPipeline分析Item
ITEM_PIPELINES = {
'myspider.pipelines. MyPipeline': 300,
}
- Spider 自定义设置
使用custom_settings
该设置是一个dict.当启动spider时,该设置将会覆盖项目级的设置. 由于设置必须在初始化(instantiation)前被更新,所以该属性 必须定义为class属性
# myspider/spiders/spider3.py
class Spider3(CrawlerSpider):
name = "spider3"
custom_settings = {
"DOWNLOAD_DELAY": 5.0,
"RETRY_ENABLED": False,
"LOG_LEVEL" : 'DEBUG',
#中间件
"DOWNLOADER_MIDDLEWARES" : {
}
#管道类
"ITEM_PIPELINES" : {
}
}
防止爬虫被ban
- 使用user agent池
- 使用IP池
- 禁止Cookie
- 增加下载延迟
- 分布式爬虫
- 一些常见设置
# settings.py
# 绕过robots策略
ROBOTSTXT_OBEY = False
# 禁用Cookie
COOKIES_ENABLED = False
# 限制爬取速度
DOWNLOAD_DELAY = 5
# 禁止重定向
REDIRECT_ENABLED = False
# 全局并发数
CONCURRENT_REQUESTS = 500
# 禁止重试
RETRY_ENABLED = False
# 减小下载超时
DOWNLOAD_TIMEOUT = 15
#下载重复次数
REIRY_ITMES=3
#请求超时
DOWNLOAD_TIMEOUT=3
常用的Middleware
- 使用代理IP
在mymiddlewares.py中间件配置
from scrapy.conf import settings
import random
import base64
#随机代理中间件 ,混合免费代理和认证代理
# 随机更换代理ip
class RandomProxy(object):
def process_request(self,request , spider):
proxy = random.choice(PROXIES) # 随机选出一个代理
if proxy.get('auth') is None: # 免费代理
request.meta['proxy'] = 'http://' + proxy['host']
else : # 收费代理
auth = base64.b64encode(proxy['auth'])
request.headers['Proxy-Authorization'] = 'Basic ' + auth
request.meta['proxy'] = 'http://' + proxy['host']
#随机代理中间件,混合免费代理和认证代理 (数据库的)
class RandomProxyMysql(object):
def __init__(self):
my=settings['MYSQL']#调用settings中的MYSQL
#连接数据库
self.conn=pymysql.connect(my['host'], my['user'], my['password'], my['db'], charset='utf8')
#创建游标对象
self.cursor=self.conn.cursor()
#发起请求执行
def process_request(self,request,spider):
# print(settings['PROXIES'])#代理
#获取代理
proxy=self.random_proxy()
#设置代理信息
request.meta['proxy']='http://%s:%s' % (proxy[1],proxy[2])
def process_response(self,request,response,spider):
print(response.status)#状态
return response#返回
def random_proxy(self):
sql = 'select * from 66ip ORDER BY rand() limit 1'
self.cursor.execute(sql)#执行
proxy = self.cursor.fetchone()#获取单个
return proxy#返回
- 随机Agent
#在mymiddlewares.py中配置
from fake_useragent import UserAgent
#定义一个中间件就是一个类 # 随机更换浏览器身份中间件
class RandomUserAgent(object):
def __init__(self):
self.ua=UserAgent()#实例化中间件类
def process_request(self,request,spider):
#随机请求头
request.headers['User-Agent']=self.ua.random
- 使用selenium中PhantomJS 抓取JS网页
#方法1
from selenium import webdriver
from scrapy.http import HtmlResponse
import time
class CustomJavaScriptMiddleware(object):
def process_request(self, request, spider):
print "PhantomJS is starting..."
driver = webdriver.PhantomJS() #指定使用的浏览器
driver.get(request.url)
time.sleep(1)
js = "var q=document.documentElement.scrollTop=10000"
driver.execute_script(js) #可执行js,模仿用户操作。此处为将页面拉至最底端。
time.sleep(1)
body = driver.page_source
print ("访问"+request.url)
return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
#方法2
rom selenium import webdriver
import time
from scrapy.http.response.html import HtmlResponse
class TaobaopaquDownloaderMiddleware(object):
def __init__(self):
#创建无界面浏览器对象(避免每次访问详情页,都会打开一个浏览器)
self.driver=webdriver.PhantomJS(executable_path=r'E:\Desktop\ceshi\phantomjs-2.1.1-windows\bin\phantomjs.exe')
def process_request(self, request, spider):
'''
:param request: 请求对象
:param spider: #爬虫名称
:return: 返回值
'''
#只处理详情页请求
if request.meta.get('phantomjs',True):
self.driver.get(request.url)#发送请求
time.sleep(2)
#获取页面
html=self.driver.page_source
# self.driver.quit()#关闭浏览器
return HtmlResponse(url=request.url,body=html,encoding='utf-8',request=request)
常用的Pipeline
过滤重复的Item
#pipelines.py
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
if item['id'] in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(item['id'])
return item
#settings.py
ITEM_PIPELINES = {
'mySpider.pipelines. DuplicatesPipeline': 301,
}
把Item存储到MySQL的Pipeline
from twisted.enterprise import adbapi
import datetime
import MySQLdb.cursors
class SQLStorePipeline(object):
def __init__(self):
self.dbpool = adbapi.ConnectionPool('MySQLdb',
host='127.0.0.1',
db='webspider',
user='mysql',
passwd='secret',
cursorclass=MySQLdb.cursors.DictCursor,
charset='utf8',
use_unicode=True
)
print("SQLStorePipeline init")
def close_spider(self, spider):
print("SQLStorePipeline closed")
def open_spider(self, spider):
print("SQLStorePipeline opend")
def process_item(self, item, spider):
if isinstance(item, myItem):
query = self.dbpool.runInteraction(self._conditional_insert, item)
query.addErrback(self._database_error, item)
return item
def _conditional_insert(self, tx, item):
try:
tx.execute(sql)
except Exception, e:
print e
def _database_error(self, e, item):
print "Database error: ", e
把Item保存到JSON文件
import json
import codecs
from collections import OrderedDict
class JsonWithEncodingPipeline(object):
def __init__(self):
self.file = codecs.open('data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(OrderedDict(item), ensure_ascii=False, sort_keys=True) + "\n"
self.file.write(line)
return item
def close_spider(self, spider):
print("JsonWithEncodingPipeline closed")
self.file.close()
def open_spider(self, spider):
print("JsonWithEncodingPipeline opend")
# @todo 把Item保存到Redis
class RedisStorePipeline(object):
pass
# @todo 把Item保存到MongoDB
class MongodbStorePipeline(object):
pass