如何以编程方式更改用户代理字符串?

4 python user-agent

我想编写一个更改我的用户代理字符串的程序.

我怎么能用Python做到这一点?

Cor*_*erg 8

我假设你的意思是HTTP请求中的用户代理字符串?这只是一个与您的请求一起发送的HTTP标头.

使用Python的urllib2:

import urllib2

url = 'http://foo.com/'

# add a header to define a custon User-Agent
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }

req = urllib2.Request(url, '', headers)
response = urllib2.urlopen(req).read()
Run Code Online (Sandbox Code Playgroud)