标签:job strong 类型 操作系统 sel 搜索 com default ack
什么是user-agent?
用户代理,服务器识别用户的操作系统,浏览器类型和渲染引擎,不同浏览器的user-agent是不同的
如何随机更改user-agent?
1. 在setting中添加user-agent列表
# setting: # 随机更换user-agent # USER_AGENT_LIST = [‘zspider/0.9-dev http://feedback.redkolibri.com/‘, # ‘Xaldon_WebSpider/2.0.b1‘, # ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) Speedy Spider (http://www.entireweb.com/about/search_tech/speedy_spider/)‘, # ‘Mozilla/5.0 (compatible; Speedy Spider; http://www.entireweb.com/about/search_tech/speedy_spider/)‘, # ‘Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0) AddSugarSpiderBot www.idealobserver.com‘, # ]
2. 在download_middleware中导入user-agent列表,每次列表中取得一个值
__author__ = ‘beimenchuixue‘ __blog__ = ‘http://www.cnblogs.com/2bjiujiu/‘ from random import choice class RandomUserAgentMiddleware(object): def __init__(self, agent_list): super(RandomUserAgentMiddleware, self).__init__() self.agent_list = agent_list @classmethod def from_crawler(cls, crawler): # 获取USER_AGENT_LIST列表 o = crawler.settings[‘USER_AGENT_LIST‘] return cls(o) def process_request(self, request, spider): if self.agent_list: # 随机取得一个值 random_user_agent = choice(self.agent_list) # 设置User-Agent值 request.headers.setdefault(b‘User-Agent‘, random_user_agent)
3. setting中注册download_middleware,把原生的置为None
DOWNLOADER_MIDDLEWARES = { ‘scrapy.downloadermiddlewares.useragent.UserAgentMiddleware‘: None, ‘JobBole.middlewares.RandomUserAgentMiddleware‘: 400, }
download_middleware类有什么用?
他是介于request和response中的钩子框架,用来全局修改request和response
还有哪些更改随机user-agent方法?
scrapy-fake-useragent -- Githup直接搜索
标签:job strong 类型 操作系统 sel 搜索 com default ack
原文地址:http://www.cnblogs.com/2bjiujiu/p/7368002.html