首页 > 解决方案 > 如何使用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)

标签: pythonpython-3.xloginpython-requests

解决方案


您可以查看浏览器控制台在您按下页面上的登录按钮时发送什么请求。您需要模拟此请求(网址和发布数据)。


推荐阅读