UA的设置:
1、在一般requests
请求中设置UA
:
方法1:
首先设置一些UA
在一个列表中,当然也可以在一个py
文件中,到时候用的时候直接导入就可以了。然后再设置headers
的时候随机取agent
中的一个。
agent = [
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
]
方法2:
使用fake-useragent
模块,用pip3 install fake-useragent
安装模块。
from fake-useragent import UserAgent
加载模块。实例化ua = UserAgent()
,然后直接使用ua.random
就可以调用模块里面的user-agent
了。
2、在scrapy
框架中设置UA
:
这里有一种简单的方法设置UA
,还是使用fake-useragent
模块,这时候需要在middlewares.py
中添加如下代码:
import random
from scrapy import signals
from fake_useragent import UserAgent
# from Dytt.settings import USER_AGENT
class RandomUserAgentMiddlware(object):
def __init__(self, crawler):
super(RandomUserAgentMiddlware, self).__init__()
self.ua = UserAgent()
@classmethod
def from_crawler(cls, clawler):
return cls(clawler)
def process_request(self, request, spider):
request.headers.setdefault("User-Agent", self.ua.random)
# print(self.ua.random)
感兴趣的可以看看fake-useragent
的源码。然后在settings.py
文件中添加这个类,并且开启DOWNLOADER_MIDDLEWARES
,如图:
useragent
,可以取消最后一行的注释,在运行程序的时候就会输出。
IP池的设置:
待更新...