1.在setting中设置User-Agent默认值;
2.将setting中DOWNLOADER_MIDDLEWARES默认的'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware':
设为NONE;
3.安装fake_useragent第三方库(用于生成随机User-Agent);
4.并定义RANDOM_UA_TYPE=“random”(“random”可以为“chrome”,“firefox”等等,用于生成不同浏览器的User-Agent)
5.在middleware.py下,生成一个随机取User-Agent的类:
class RandomUserAgentMiddleware(object):
#随机更换user-agent
def __init__(self,crawler):
super(RandomUserAgentMiddleware,self).__init__()
self.ua = UserAgent()
self.ua_type = crawler.settings.get("RANDOM_UA_TYPE","random")
@classmethod
def from_crawler(cls,crawler):
return cls(crawler)
def process_request(self,request,spider):
def get_ua():
return getattr(self.ua,self.ua_type)
request.headers.setdefault('User-Agent',get_ua())
6.把该类配置到DOWNLOADER_MIDDLEWARES:
DOWNLOADER_MIDDLEWARES = {
'ArticleSpider.middlewares.RandomUserAgentMiddleware': 543,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
}
7.配置完成后,直接运行spider,headers中的User-Agent取随机值。