I need log in to a site using python. This site uses cookies.
I've tried using urllib2
and requests
libraries and this answer to a related question.
# -*- coding:utf-8 -*-
import cookielib
import urllib
import urllib2
import requests
auth_data = {
'login': '+79269999999',
'password': 'strongpassword',
'source': 'MENU',
}
urls = {
'home': r'https://qiwi.ru',
'login': r'https://qiwi.ru/auth/login.action',
'reports': r'https://qiwi.ru/report/list.action',
}
headers = {
#'content-type': 'application/json',
'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Referer': 'qiwi.ru',
}
def requests_foo():
with requests.session() as c:
c.get(urls['home'])
request = c.post(urls['login'], data=auth_data, headers=headers)
print request.headers['content-type']
print request.status_code
def urllib_foo():
cj = cookielib.CookieJar()
opener = urllib2.build_opener(
urllib2.HTTPSHandler(),
urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode(auth_data)
request = urllib2.Request(urls['home'], login_data, headers)
opener.open(request)
try:
request = urllib2.Request(urls['login'], login_data, headers)
resp = opener.open(request)
except IOError, e:
print e
else:
print resp.read()
But both functions return HTTP Error 401: Unauthorized
What should I do for log in on site?
EDIT
I tried using mechanize, but without success
def is_logged_in(html):
return auth_data['login'] in html
def mechanize_foo():
br = mechanize.Browser()
br.open(urls['home'])
br.select_form(nr=0)
forms = [f for f in br.forms()]
forms[0].action = urls['login']
forms[0]['login'] = auth_data['login']
forms[0]['password'] = auth_data['password']
response = br.submit()
print is_logged_in(response.read())