我需要使用python登录到一个站点。此网站使用Cookie。
我尝试过使用urllib2
和requests
库和这个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()
但这两个函数都返回HTTP错误401:Unauthorized
我应该如何登录网站?在
编辑
我尝试使用机械化,但没有成功
^{pr2}$
我担心浏览网站并不是我们所要求的。如果要模拟web浏览器,则需要使用名为
mechanize
的库。在您可以继续这样做,但过一段时间后,它将变得非常烦人,因为您将需要设置大量的样板代码。在
这是我所知道的唯一能做到这一点的工具,可能还有其他工具。Here是指向站点的链接,您可以在那里学习如何在Python中使用它。在
编辑
你也可以使用硒。从here下载。在
用于测试firefox系统登录。 主页连接到
login.action
两次。在第一次它发送},并使用一些
login
、password
和{token
获取JSON数据。在{{cd2>
所以到这个服务器的连接就更复杂了。在
如果你没有经验,最好试试Selenium或Mechanize(参见游戏Brainiac答案)。在
相关问题 更多 >
编程相关推荐