Python机械化HTTP Basic Auth的实现

时间:2016-12-01 20:12:16

标签: python-2.7 http-auth

我可以使用请求来使用HTTP基本身份验证:

import requests
request = requests.post(url, auth=(user, pass), data={'a':'whatever'})

还使用urllib2和urllib:

import urllib2, urllib
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, pass)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
content = urllib2.urlopen(url, urllib.urlencode({'a': 'whatever'}))

问题是当我使用mechanize尝试相同的操作时,我收到了未经授权的错误:

import mechanize, urllib
from base64 import b64encode

browser = mechanize.Browser()
b64login = b64encode('%s:%s' % (user, pass))
browser.addheaders.append(('Authorization', 'Basic %s' % b64login ))
request = mechanize.Request(url)
response = mechanize.urlopen(request, data=urllib.urlencode({'a':'whatever}))

错误:

HTTPError: HTTP Error 401: UNAUTHORIZED

我尝试使用mechanize的代码可能试图以与其他两个代码片段不同的方式进行身份验证。所以问题是如何在机械化中实现相同的认证过程。 我使用的是python 2.7.12

1 个答案:

答案 0 :(得分:2)

标题应该已添加到请求而不是浏览器中。实际上甚至不需要浏览器变量。

import mechanize, urllib
from base64 import b64encode

b64login = b64encode('%s:%s' % (user, pass))

request = mechanize.Request(url)
request.add_header('Authorization', 'Basic %s' % b64login )
response = mechanize.urlopen(request, data=urllib.urlencode({'a':'whatever'}))