如何使用python的urllib设置标头?

ewo*_*wok 65 python header http urllib

我对python的urllib很新.我需要做的是为发送到服务器的请求设置自定义标头.具体来说,我需要设置Content-type和Authorizations标头.我查看了python文档,但是我找不到它.

Cor*_*erg 82

使用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()
Run Code Online (Sandbox Code Playgroud)


Cee*_*man 75

对于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)
Run Code Online (Sandbox Code Playgroud)

  • @ user3378649可能是您的意思是使用`requests` python程序包[custom headers](http://docs.python-requests.org/en/master/user/quickstart/#custom-headers) (2认同)
  • 这个答案 - 一千次是(谢谢!)。我一直在努力寻找 python 2 和 3(在 urllib、urllib2 和 urllib3 之间)的通用接口。 (2认同)

sle*_*erd 16

使用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()
Run Code Online (Sandbox Code Playgroud)

未经测试....