标签:middle his mile def value 技术 sig lan over
fake_useragent第三方库,来实现随机请求头的设置;
GitHub ---> https://github.com/hellysmile/fake-useragent
安装 ---> pip3 install fake-useragent
查看useragent ---> http://fake-useragent.herokuapp.com/browsers/0.1.5
关键是后面的版本号,如果更新后使用原版本号就查看不到useragent;
如何操作最新版本号?通过pip3 list 查看安装的版本号;
使用
from fake_useragent import UserAgent ua = UserAgent() print(ua.ie) #随机打印ie浏览器任意版本 print(ua.firefox) #随机打印firefox浏览器任意版本 print(ua.chrome) #随机打印chrome浏览器任意版本 print(ua.random) #随机打印任意厂家的浏览器
首先在middlewares.py中自定义随机请求头的类
根据scrapy源码中: scrapy目录--->downloadermiddlewares--->useragent.py 中的 UserAgentMiddleware类来写middlewares.py随机请求头的类
源码中useragent.py
"""Set User-Agent header per spider or use a default value from settings""" from scrapy import signals class UserAgentMiddleware(object): """This middleware allows spiders to override the user_agent""" def __init__(self, user_agent=‘Scrapy‘): self.user_agent = user_agent @classmethod def from_crawler(cls, crawler): o = cls(crawler.settings[‘USER_AGENT‘]) crawler.signals.connect(o.spider_opened, signal=signals.spider_opened) return o def spider_opened(self, spider): self.user_agent = getattr(spider, ‘user_agent‘, self.user_agent) def process_request(self, request, spider): if self.user_agent: request.headers.setdefault(b‘User-Agent‘, self.user_agent)
middlewares.py定义随机请求头的类
class RandomUserAgentMiddlware(object):
‘‘‘随机更换user-agent,基本上都是固定格式和scrapy源码中useragetn.py中UserAgentMiddleware类中一致‘‘‘
def __init__(self,crawler): super(RandomUserAgentMiddlware,self).__init__() self.ua = UserAgent()
#从配置文件settings中读取RANDOM_UA_TYPE值,默认为random,可以在settings中自定义 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())
settings里面的配置
DOWNLOADER_MIDDLEWARES = {
‘ArticleSpider.middlewares.RandomUserAgentMiddlware‘: 543, #将在middlewares.py中定义了RandomUserAgentMiddlware类添加到这里; ‘scrapy.downloadermiddlewares.useragent.UserAgentMiddleware‘:None, #需要将scrapy默认的置为None不调用 } RANDOM_UA_TYPE = "random" #或者指定浏览器 firefox、chrome...
PS:配置好后取消原来spider中定义的User-Agent。再次进行爬虫时,会自动携带随机生成的User-Agent,不需要在每个spider中自定义了;
转自https://www.cnblogs.com/qingchengzi/p/9633616.html
Python3中通过fake_useragent生成随机UserAgent
标签:middle his mile def value 技术 sig lan over
原文地址:https://www.cnblogs.com/cangqinglang/p/12573782.html