python - 如何使用python请求通过登录页面登录?
问题描述
我在网上查看了其他示例,但我似乎无法弄清楚如何登录。页面看起来像这样:
<div class="Loginbox">
<form id="login_form" name="login_form" method="post" action="/a/login.seam" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="login_form" value="login_form" />
<div>
<p><label for="login_form:name">
Username</label><br /><input id="login_form:name" type="text" name="login_form:name"/>
</p>
</div>
<div><label for="login_form:password">
Password</label><br /><input id="login_form:password" type="password" name="login_form:password" value=""/>
</div>
<div><input id="login_form:submit" type="submit" name="login_form:submit" value="Login" class="buttonmed" />
</div><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-13463453453453:3453445345345345345" autocomplete="off" />
</form>
</div>
我尝试过这样的事情:
with requests.Session() as sess:
data = {}
data['login_form:name'] = user
data['login_form:password'] = password
sess.headers = HEADERS
sess.get(url)
sess.post(url, data=data)
h = sess.get(url)
print(h.text)
但是文字仍然显示我在登录页面。
解决方案:
import requests
from bs4 import BeautifulSoup
with requests.Session() as sess:
data = {}
data['login_form'] = 'login_form'
data['login_form:name'] = user
data['login_form:password'] = password
sess.headers = HEADERS
g = sess.get(url)
soup = BeautifulSoup(g.text, "lxml")
val = soup.select_one("input[id='javax.faces.ViewState']")['value']
data['javax.faces.ViewState'] = val
h = sess.post(url, data=data)
print(h.text)
解决方案
您可以查看浏览器控制台在您按下页面上的登录按钮时发送什么请求。您需要模拟此请求(网址和发布数据)。
推荐阅读
- amazon-web-services - AmazonCloudWatch PutMetricData 请求格式解析
- css - Mat Paginator背景颜色更改通过Css
- c - 使用 libgit2 变基
- flutter - Real Phone 上的 Flutter 键盘调整大小问题
- numpy - 设置 Axes3D 对象的轴刻度
- google-sheets - 如何计算旁边有状态的多个范围?
- react-native - 世博会多个本地通知未按时触发
- sql - SQL JOIN 使用两个条件和部分匹配的两个表
- sql - Rank最新记录
- python - PyInstaller 错误:FileNotFoundError:[Errno 2] 没有这样的文件 ot 目录:'myKivyfile.kv'