我试图使用python脚本登录,目的是为了个人使用而抓取我的一些数据。在我尝试登录(使用脚本)后,当前收到422“无法处理的更改”消息。
我相信我的有效载荷遗漏了一些东西。我现在有我的电子邮件、通行证和来自隐藏输入字段的令牌。还有什么是我应该包括的吗?谢谢!
下面是我的代码。这是几种方法的组合。其中一个位于这里:https://brennan.io/2016/03/02/logging-in-with-requests/
这里:http://kazuar.github.io/scraping-tutorial/
import requests
import lxml.html
from bs4 import BeautifulSoup
def cas_login(service, username, password):
params = {'service':service}
LOGIN_URL = "https://stmarys-ca.onelogin.com/login"
# Start session and get login form.
session = requests.session()
login = session.get(LOGIN_URL, params=params)
# Get the hidden elements and put them in our form.
login_html = lxml.html.fromstring(login.text)
hidden_elements = login_html.xpath('//form//input[@type="hidden"]')
# "Fill out" the form.
form = {
"email": str(username),
"password" : str(password)
}
token = {x.attrib['value'] for x in hidden_elements}
form['authenticity_token'] = token
# Finally, login and return the session.
r = session.post(LOGIN_URL, data=form, params=params)
#End of tutorial
return session,r
def main():
response, resp = cas_login('https://www.stmarys-ca.edu/sessions', 'USER_EMAIL', 'USER_PASS')
print(resp.url)
print(resp.text)其中USER_EMAIL和USER_PASS是个人信息,resp.url返回登录URL,而不是参数resp.text中包含的服务URL返回带有错误代码的html页面。
有什么想法?谢谢!
发布于 2018-02-19 13:52:38
幸运地解决了这个问题,把答案张贴出来,让其他人可以看到。
我添加了以下内容:
headers = dict(referer = LOGIN_URL)添加到我的post请求,其中LOGIN_URL是上面代码中的局部变量
https://stackoverflow.com/questions/48859662
复制相似问题