Python - urllib2如何知道您的授权是否成功

时间:2014-09-17 09:59:19

标签: python login request authorization urllib2

当您通常登录网站时,我们可以使用urllib2.Request。

import urllib2, base64
req = urllib2.Request("http://www.facebook.com/")
base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
req.add_header("Authorization", "Basic %s" % base64string)
requested = urllib2.urlopen(req)

但我们如何知道授权是否成功?因为您可能只是打开了错误授权的URL。

1 个答案:

答案 0 :(得分:1)

如果您未获得授权并且返回401状态,则会引发urllib2.HTTPError异常:

>>> import urllib2, base64
>>> req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
>>> base64string = base64.encodestring("%s:%s" % ("username", "password")).replace("\n", "")
>>> req.add_header("Authorization", "Basic %s" % base64string)
>>> urllib2.urlopen(req)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: UNAUTHORIZED

成功授权后,您将获得一个响应对象:

>>> req = urllib2.Request('http://httpbin.org/basic-auth/foouser/barpw')
>>> base64string = base64.encodestring("%s:%s" % ("foouser", "barpw")).replace("\n", "")
>>> req.add_header("Authorization", "Basic %s" % base64string)
>>> response = urllib2.urlopen(req)
>>> response.getcode()
200