2017-12-28 5 views
1

Ich lerne Python-Vernetzung. Ich hatte Socket gelernt und jetzt möchte ich Python HTTP lernen, um eine Verbindung zu HTTPServer herzustellen, Cookies zu extrahieren usw. Ich stehe vor diesem Problem mit der Cookie-Extraktion. Versuche google aber keine Lösung gefunden, hier ist der Code:python cookielib Fehler: 403 verboten

import cookielib 
import urllib 
import urllib2 

ID_USERNAME= 'id_username' 
ID_PASSWORD = 'id_password' 
USERNAME = '[email protected]' 
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() 

Dies ist der Fehler:

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 

Antwort

0

Sie senden Ihre Login-Daten als Daten POST und nicht als Teil der URL .

>>> url = 'https://bitbucket.org/account/signin/' 
>>> user = '[email protected]' 
>>> 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 
+0

Vielen Dank snakecharmerb.It löste mein Problem, danke. – joe