我正在尝试从SSO(单一登录)站点的后面下载一些文件。似乎已通过SAML身份验证,这就是我遇到的问题。通过身份验证后,我将能够执行返回JSON的API请求,因此无需解释/抓取。
不太确定如何在Mechanicalsoup中解决该问题(并且通常不太熟悉Web编程),我们将不胜感激。
这是我到目前为止所拥有的:
import mechanicalsoup
from getpass import getpass
import json
login_url = ...
br = mechanicalsoup.StatefulBrowser()
response = br.open(login_url)
if verbose: print(response)
# provide the username + password
br.select_form('form[id="loginForm"]')
print(br.get_current_form().print_summary()) # Just to see what's there.
br['UserName'] = input('Email: ')
br['Password'] = getpass()
response = br.submit_selected().text
if verbose: print(response)
[此时,我看到一个页面,告诉我javascript已被禁用,必须单击提交以继续。所以我这样做:
br.select_form()
response = br.submit_selected().text
if verbose: print(response)
在那我抱怨状态信息丢失。
输出:
<h2>State information lost</h2>
State information lost, and no way to restart the request<h3>Suggestions for resolving this problem:</h3><ul><li>Go back to the previous page and try again.</li><li>Close the web browser, and try again.</li></ul><h3>This error may be caused by:</h3><ul><li>Using the back and forward buttons in the web browser.</li><li>Opened the web browser with tabs saved from the previous session.</li><li>Cookies may be disabled in the web browser.</li></ul>
我发现唯一在SAML登录后进行抓取的命中注定都是采用硒方法(有时会下降到请求中)。
机械汤可以吗?
我的情况证明需要Javascript登录。我最初关于进入SAML身份验证的问题不是真正的环境。因此,这个问题尚未得到真正回答。感谢@Daniel Hemberger帮助我在评论中指出这一点。
在这种情况下,MechanicalSoup不是正确的工具(由于Javascript),我最终使用了selenium to get through authenication then using requests。