2016-12-01 57 views
2

我能得到HTTP基本身份驗證使用要求的工作:Python的機械化實現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'})) 

的問題是,我得到一個未經授權的錯誤當我嘗試與機械化相同的東西:

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 

我嘗試機械化的代碼可能試圖以不同於其他兩個代碼片段的方式進行身份驗證。所以問題是如何在機械化中實現相同的認證過程。 我正在使用python 2.7.12

回答

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