我在使用Python请求自动化以下站点的登录过程时遇到了一些麻烦:https://www.smartmetertexas.com/CAS/public
目的是填写并提交表单数据,然后继续进行Web抓取的登录页面。我和刮痧一样陌生,所以我很抱歉,如果这里有一个明显的错误我完全忽略了。
我想我已经正确地确定了表单中的必要元素(使用元素id,我希望是正确的答案)
形成:
<form action="/pkmslogin.form" method="post" name="Public_index"
id="Public_index" autocomplete="off"> <input type="password" name="pass_dup"
style="display:none">
用户名:
<input name="username" autocomplete="off" id="username" tabindex="1"
value="" type="text" class="txtID" title="You must provide a User ID"
maxlength="100">
密码:
<input name="password" autocomplete="off" id="txtPassword" type="password"
tabindex="2" class="txtPW" title="You must provide a Password"
maxlength="24">
登录按钮:
<input type="submit" name="logIn" value="Log In" title="Type your User ID,
Password, and click Log In to access your account" onclick="return
loginckecks(this.form)">
这是自动登录过程的死简单脚本:
import requests
import sys
import time
USERNAME = 'test1'
PASSWORD = 'password1'
LOGIN_URL = 'https://www.smartmetertexas.com/CAS/public/pkmslogin.form'
PROTECTED_URL = 'https://www.smartmetertexas.com/texas/wps/myportal'
#dict for login
login_data = {
'username': USERNAME,
'txtpassword': PASSWORD,
'submit': 'logIn',
}
with requests.Session() as session:
#Perform login
post = session.post(LOGIN_URL, data = login_data)
#Wait 20 seconds for login to complete
#time.sleep(15)
# Print the html
result = session.get(protected_URL)
print(result.text)
所有登录尝试都失败,此外,重定向页面似乎与在具有错误用户名和密码的Web浏览器中显示的页面不同。我非常感谢有关本网站细节的直接答复。
如果您尝试使用请求登录。这条代码对我有用。我只使用了请求模块而不是selenium。这样做的方法基本上是通过使用开发工具检查标头和浏览器发送的请求。我在youtube上关注了this教程以了解它。我希望你觉得这有帮助。我也在尝试做一些与你相似的事情。所以,如果你取得任何进展,请告诉我。
import requests
from bs4 import BeautifulSoup
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'
}
login_data = {
# 'pass_dup': '',
'username': 'youruser',
'password': 'password',
# 'buttonName': '',
'login-form-type': 'pwd'
}
with requests.Session() as s:
url = 'https://www.smartmetertexas.com/pkmslogin.form'
r = s.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
r = s.post(url, data=login_data, headers=headers)
print(r.content)