每次我开始打开网址时,我都试图让Mechanize使用随机的User-Agent。 有人能指出我需要采取的正确方向才能做到这一点吗? - 我到处搜索,找不到参考资料。
谢谢!
答案 0 :(得分:1)
此link为您提供示例User-Agent参考。演示它的示例代码:
from random import choice
user_agents = ['Mozilla/5.0 (X11; U; Linux; i686; en-US; rv:1.6) Gecko Debian/1.6-7','Konqueror/3.0-rc4; (Konqueror/3.0-rc4; i686 Linux;;datecode)','Opera/9.52 (X11; Linux i686; U; en)']
random_user_agent = choice(user_agents)
您可以将上述链接中包含的user_agents数量包含在变量user_agents中。
现在只需通过在初始化过程中添加标题将random_user_agent
放入Mechanize。
答案 1 :(得分:0)
我在使用网络抓取工具时遇到了同样的问题,这是我使用的解决方案:
class URLOpener():
def opener(self,user_agent):
cj=cookielib.CookieJar()
#Process Hadlers
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders=[
('User-Agent', user_agent),
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
('Accept-Language', 'en-gb,en;q=0.5'),
('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
('Keep-Alive', '115'),
('Connection', 'keep-alive'),
('Cache-Control', 'max-age=0'),
]
return opener
#Openers with different User-Agents
def opener_list(self,f_path):
#f_path is a path to the file that contains browsers
f=open(f_path, 'r+')
count=0
user_agent_list=list()
for line in f.xreadlines():
count+=1
user_agent_list.append(line[:-1])
openers=[self.opener(user_agent) for user_agent in user_agent_list]
return openers
我创建的文件看起来与之类似:
Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Mozilla/5.0 (Linux; U; Android 2.3; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9
Mozilla/5.0 (Linux; U; Android 2.3.5; zh-cn; HTC_IncredibleS_S710e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.5; en-us; HTC Vision Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.4; fr-fr; HTC Desire Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; T-Mobile myTouch 3G Slide Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC_Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC_Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari
Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1