抓取__hpKey的网站,然后在python中使用请求和beautifulsoup登录

问题描述 投票:0回答:1

这是我的第一个编码项目,因此我可能不正确理解所有术语。我正在尝试使用python中的请求和BeautifulSoup库登录NHS献血网站。我已经做到了,但是仅当我使用“ __hpKey”的值时才有效,该值是我从浏览器的“网络”选项卡的“登录标题”中复制并粘贴的。我希望能够抓取该网站以找到此令牌,而不必使用我复制并粘贴的令牌。

我设法找到'__hpKey',但是尝试登录时此键似乎不起作用。

s = requests.session()
soup_key = BeautifulSoup(s.get('https://my.blood.co.uk/Account/SignIn').content, 'html.parser')
key = soup_key.find('input', {'name': '__hpKey'})['value']

我刚刚从网络登录选项卡中输入了“密钥”值,因为使用上面的代码无法成功登录。我缩小了需要传递给登录门户的四个元素。这些是:

data = {
  'LoginEmailAddress': 'email',
  'LoginPassword': 'password',
  'Question-Reason': '',
  '__hpKey': 'key'                ## 'key' is a 216 character key ending in ==

然后,我将这4个元素传递到登录门户,并使用BeautifulSoup解析带有我的捐助者资料的网页标题。标题让我知道它是否已成功登录。

login_req = s.post('https://my.blood.co.uk/Account/Login', data=data)
soup = BeautifulSoup(s.get('https://my.blood.co.uk/Home/Landing?load=Yourdonations').content, 'html.parser')
print(soup.title)       # If logged in prints "My Donor Record", else prints "My Donor Record - Sign in or Register"

所以,我如何找到一个传递给登录门户的'__hpKey'值?

谢谢

python python-3.x web-scraping python-requests forms-authentication
1个回答
0
投票

请求中包含一些验证字段。这些字段位于表单的隐藏input标记中。最快的方法是在表单下获取所有输入,然后按原样发送所有输入:

import requests
from bs4 import BeautifulSoup

s = requests.Session()

email = "[email protected]"
password = "your_password"

r = s.get("https://my.blood.co.uk/Account/SignIn")
soup = BeautifulSoup(r.text, "html.parser")
form = soup.findAll("form")[1]

payload = dict([
    (t["name"],t["value"]) 
    for t in form.findAll("input")
    if t.has_attr("value")
])
payload["Type-Fax"] = "" # maybe not necessary ?
payload["LoginEmailAddress"] = email
payload["LoginPassword"] = password

print(payload)
r = s.post("https://my.blood.co.uk/Account/Login", data = payload)

soup = BeautifulSoup(s.get('https://my.blood.co.uk/Home/Landing?load=Yourdonations').content, 'html.parser')
print(soup.title)

注意,我尚未使用有效的帐户测试以上代码

© www.soinside.com 2019 - 2024. All rights reserved.