在python 3中添加身份验证标头

时间:2016-04-11 20:16:41

标签: python python-3.x authentication urllib2 urllib

使用urllib2库和add_header函数,我能够在python 2.7中验证和检索数据。但是由于urllib2库在python 3中更多,我如何用urllib库添加Basic Authentication头?

1 个答案:

答案 0 :(得分:1)

请检查import urllib.request req = urllib.request.Request('http://www.example.com/') req.add_header('Referer', 'http://www.python.org/') r = urllib.request.urlopen(req) 的请求类的add_header方法。

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')

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

gecpLU

(取自同一页)