无法在python中获得授权

时间:2015-03-26 14:02:04

标签: python http authentication

我尝试了以下两种方法,但对我来说都没有用。

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, top_level_url, user, passwd)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)

request = urllib2.Request(temp)
# You need the replace to handle encodestring adding a trailing newline 
# (https://docs.python.org/2/library/base64.html#base64.encodestring)
base64string = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
#print base64string
request.add_header("Authorization", "Basic %s" % base64string)   
request.add_header('User-agent', 'Mozilla/5.0')   
f = urllib2.urlopen(request)

我可以检索链接

http://www.cd-pa.com/bbs/?2880

但没办法让它起作用

http://www.cd-pa.com/bbs/home.php?mod=space&uid=14476&do=album&id=6571'

任何人都能发光吗?谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用

  

base64.b64encode( “{用户名}:{密码}”。格式(用户名,密码))

用于生成base64string