使用Python登录网站

时间:2016-11-13 08:07:25

标签: python authentication web-scraping

这个问题已经解决了各种形状和风格,但我无法应用我在网上阅读的任何解决方案。

我想使用Python登录网站:https://app.ninchanese.com/login 然后到达页面:https://app.ninchanese.com/leaderboard/global/1

我尝试了各种各样的东西,但没有成功...... 使用POST方法:

@messages = Message.all

使用来自请求包的身份验证功能

import urllib
import requests
oURL = 'https://app.ninchanese.com/login'
oCredentials = dict(email='myemail@hotmail.com', password='mypassword')
oSession = requests.session()
oResponse = oSession.post(oURL, data=oCredentials)
oResponse2 = oSession.get('https://app.ninchanese.com/leaderboard/global/1')

每当我打印oResponse2时,我都会看到我总是在登录页面上,所以我猜测认证不起作用。

你能告诉我们如何实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

您必须发送csrf_token以及您的登录请求:

import urllib
import requests
import bs4

URL = 'https://app.ninchanese.com/login'
credentials = dict(email='myemail@hotmail.com', password='mypassword')
session = requests.session()
response = session.get(URL)
html = bs4.BeautifulSoup(response.text)
credentials['csrf_token'] = html.find('input', {'name':'csrf_token'})['value']
response = session.post(URL, data=credentials)
response2 = session.get('https://app.ninchanese.com/leaderboard/global/1')
相关问题