- pip install fake-useragent -i https://pypi.tuna.tsinghua.edu.cn/simple
- pip install -U fake-useragent -i https://pypi.tuna.tsinghua.edu.cn/simple
- from fake_useragent import UserAgent
-
-
- class RandomUserAgentMidddlware(object):
- def __init__(self, crawler):
- super(RandomUserAgentMidddlware, 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):
- request.headers['User-Agent'] = getattr(self.ua, self.ua_type)
- DOWNLOADER_MIDDLEWARES = {
- 'announcement.middlewares.RandomUserAgentMidddlware': 542,
- }