我需要使用 python 登录到一个站点。本网站使用 cookie。我尝试过使用urllib2
和requests
库以及相关问题的答案。
# -*- 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()
但是这两个函数都返回HTTP 错误 401:未经授权
现场登录应该怎么做?
编辑
我尝试使用mechanize,但没有成功
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())