如何使用Python的urllib设置HTTP头?

103
我对Python的urllib还不太熟悉。我需要做的是为发送到服务器的请求设置自定义的HTTP头。
具体来说,我需要设置Content-TypeAuthorization HTTP头。我已经查阅了Python文档,但没有找到相关内容。
4个回答

135

对于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)

我们能使用requests q.add_header('apikey', 'xxx')做同样的事吗? - user3378649
你是什么意思,@user3378649? - Cees Timmerman
2
@user3378649 可能你想使用 requests Python 包的自定义头部功能。 - WeizhongTu
2
这个答案 - 一千次肯定(谢谢!)。我已经苦苦挣扎了几个小时,试图找到 Python 2 和 3 的通用接口(在 urllib、urllib2 和 urllib3 之间)。 - Beorn Harris

104

使用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()

22

使用urllib2创建一个Request对象,然后将其交给urlopen处理。 http://docs.python.org/library/urllib2.html

我不再使用“旧”版本的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()

未测试的...


1

对于多个标题,请按以下方式操作:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

2
如果您有多个标题字段要使用,请不要这样做,只需传递一个标题字典即可。 - Raleigh L.
1
你猜得对 - 但是嘿,这是针对Python 2.7的2015年的情况。 现在 - 我正在填充一个字典。 - Gil Allen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接