如何使用Python的urllib设置HTTP头?
我对Python的urllib还很陌生。我需要做的是为发送到服务器的请求设置一个自定义的HTTP头。
具体来说,我需要设置Content-Type
和Authorization
这两个HTTP头。我查阅了Python的文档,但一直找不到相关的信息。
4 个回答
22
使用urllib2库,创建一个请求对象,然后把这个对象交给urlopen来处理。
我现在不太使用“旧版”的urllib了。
req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()
这个代码还没有经过测试……
138
对于Python 3和Python 2,这段代码都可以正常运行:
try:
from urllib.request import Request, urlopen # Python 3
except ImportError:
from urllib2 import Request, urlopen # Python 2
req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()
print(content)
107
使用 urllib2 添加 HTTP 头信息:
来自文档的内容:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()