在 python 3 中添加身份验证 header

Adding authentication header in python 3

使用 urllib2 库和 add_header 函数,我能够在 python 2.7 中验证和检索数据。但由于 urllib2 库更多地出现在 python 3 中,我如何添加基本身份验证 header 和 urllib 库?

请检查 urllib.request 请求 class 的 add_header 方法。

import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib.request.urlopen(req)

顺便说一下,我建议你用另一种方式检查,使用 HTTPBasicAuthHandler:

import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

(取自同一页)