python cookielib错误:403禁止

时间:2017-12-28 10:28:52

标签: python http cookies

我正在学习python网络。我已经学习了socket,现在我想学习python HTTP连接到HTTPServer,提取cookie等。我正在用cookie提取来解决这个问题。尝试了谷歌,但没有找到解决方案,这里是代码:

import cookielib
import urllib
import urllib2

ID_USERNAME= 'id_username'
ID_PASSWORD = 'id_password'
USERNAME = 'you@email.com'
PASSWORD = 'mypassword'
LOGIN_URL = 'https://bitbucket.org/account/signin/?next=/'
NORMAL_URL = 'https://bitbucket.org/'

def extract_cookie_info():
        cj=cookielib.CookieJar()
        login_data= urllib.urlencode({ID_USERNAME : USERNAME,ID_PASSWORD:PASSWORD})
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        resp = opener.open(LOGIN_URL,login_data)
        for cookie in cj:
               print "First time cookie: %s ----> %s" %(cookie.name,cookie.value)
               print "Headers: %s"%resp.headers
        resp = opener.open(NORMAL_URL)
        for cookie in cj:
                print "Second time cookie: %s --> %s"%(cookie.name,cookie.value)
                print "Headers : %s"%resp.headers


if __name__ == '__main__':
         extract_cookie_info()

这是错误:

Traceback (most recent call last):
  File "e.py",line 27,in <module>
    extract_cookie_info()
  File "e.py",line 16,in extract_cookie_info
    resp=opener.open(LOGIN_URL,login_data)
  File "C:\Python27\lib\urllib2.py",line 435, in open
    response = meth(req,response)
  File "C:\Python27\lib\urllib2.py", line 548, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 473, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 556, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

1 个答案:

答案 0 :(得分:0)

您将登录详细信息作为POST数据发送,而不是作为网址的一部分发送。

>>> url = 'https://bitbucket.org/account/signin/'
>>> user = 'foo@example.com'
>>> pwd = 'secret'
>>> d = urlencode({'ID_USERNAME': user, 'ID_PASSWORD': pwd})
>>> cj = cookielib.CookieJar()
>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
>>> resp = opener.open(url + '?' + d)
>>> res.getcode()
200
>>> for cookie in cj:print cookie.name
... 
csrftoken