登录并重定向到 https://www.fpl.com/northwest/my- 后,我尝试从 https://www.fpl.com/my-account/login.html 抓取数据帐户/能源仪表板。我检查了该网站并找到了用户名:
<input id="emailOrUserId" required="required" type="text">
和密码:<input id="pwd" required="required" type="password">
HTML 字段。在重定向 URL 上,我还找到了我想要抓取的表格:<table class="v-datatable v-table theme--light"
。
使用 requests 包和 BeautifulSoup 我尝试了以下操作:
import requests
from bs4 import BeautifulSoup
payload = {
'emailOrUserId': "[email protected]",
'pwd': "password"
}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'}
loginUrl = "https://www.fpl.com/my-account/login.html"
dashboardUrl = "https://www.fpl.com/northwest/my-account/energy-dashboard"
with requests.Session() as session:
post = session.post(loginUrl, data = payload, headers = headers)
#r = session.get(loginUrl, headers = headers)
#print(r.content)
#Make request after login to other url within session
request = session.get(dashboardUrl)
print(request.text)
soup = BeautifulSoup(request.text, "lxml")
table = soup.find("table", class_ = "v-datatable v-table theme--light")
print(table)
这段代码似乎找不到表,并且总是返回“None”。打印出第一个
session.post()
调用的结果表明登录失败。我想我遗漏了一些关于帖子消息格式的重要内容。 这个 StackOverflow 问题 提供了一些奇妙的见解。我只需要有关我的特定用例的技术细节的更多帮助。
我不相信正在使用 CSRF 令牌,但可能会使用其他东西作为简单的安全措施。
如有任何帮助,我们将不胜感激!
如果您在运行 Chrome 开发者工具(或同等工具)的情况下登录该网站 (https://www.fpl.com/my-account/login.html),您会发现登录不是正常的来自
<form>
元素的 HTTP POST,但实际上是由 javascript 触发的。
当我这样做时,我看到 GET 被触发到 https://www.fpl.com/cs/customer/v1/registration/loginAndUseMigration?migrationToggle=Y
此 GET 请求包含以下 HTTP 标头:
Authorization: Basic Zm9vYmFyOmJheg==
这是标准的“基本身份验证”机制,您可以从
requests
使用该机制,如下所述:
https://requests.readthedocs.io/en/latest/user/authentication/
由于我在此网站上没有真实帐户,因此我实际上无法完全遵循登录流程,但您可能必须从此时开始并使用开发人员工具迭代地完成它查看如何管理代币。
作为一个盲目的尝试,您可以尝试使用
requests
中设置的基本身份验证 GET 到达最终所需的页面,看看这是否足以登录,如下所示:
basic = HTTPBasicAuth('user', 'pass')
requests.get('https://www.fpl.com/northwest/my-account/energy-dashboard', auth=basic)
但是,您可能会发现这还不够,您必须从
loginAndUseMigration
开始。
此外,您可能还会发现您的最终页面需要 javascript 来呈现,在这种情况下,仅靠
requests
不足以抓取它。