如何使用python请求登录多个页面的CAS?

时间:2018-04-07 22:21:54

标签: python python-requests cas

我正在尝试使用python请求登录我大学的CAS。我在网上看过一些教程和帖子,但它们都适用于CAS,它在同一页面上有用户名和密码字段。这是我要登录的网站:https://cas.tamu.edu/cas/login?service=https://howdy.tamu.edu/uPortal/Login&renew=true

正如您所看到的,只有一个用户名字段,然后在点击提交后,您将进入同一页面,现在只有该字段用于输入密码。这是我当前的代码不起作用:

import requests
import lxml.html
from bs4 import BeautifulSoup

# URL of webpage
login_url = "https://cas.tamu.edu/cas/login?service=https://howdy.tamu.edu/uPortal/Login&renew=true"
howdy = "https://howdy.tamu.edu/uPortal/normal/render.uP"
username = # my username
password = # my password

# create a session to store cookies
sesh = requests.session()

params = {'service': howdy}
# gets the URL and converts the text of the HTML code
req = sesh.get(login_url, params=params)
html_content = req.text

print html_content

# parsing the page for hidden inputs
login_html = lxml.html.fromstring(html_content)
hidden_inputs = login_html.xpath(r'//form//input[@type="hidden"]')
user_form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs}
print(user_form)

user_form["username"] = username
user_response = sesh.post(login_url, data=user_form)

print user_response.url

# same thing for the password page
pass_form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs}
print(pass_form)

pass_form["password"] = password
pass_response = sesh.post(user_response.url, data=pass_form)

print pass_response.url

我的基础是本教程:https://brennan.io/2016/03/02/logging-in-with-requests/。特别是有关CAS的部分。

1 个答案:

答案 0 :(得分:1)

我找到了一个不完全符合我想要的解决方法,但是符合我的目的。我发布这个以防万一有人发现这个类似的问题。我使用browsercookie来使用chrome中的当前cookie,所以如果我已经登录,那么我可以访问CAS后面的信息。这篇文章中的更多信息:https://stackoverflow.com/a/29628188/9613156