我正在尝试使用 python 请求登录论坛。这是我要登录的论坛:http://fans.heat.nba.com/community/
这是我的代码:
import requests
import sys
URL = "http://fans.heat.nba.com/community/index.php?app=core&module=global§ion=login"
def main():
session = requests.Session()
# This is the form data that the page sends when logging in
login_data = {
'ips_username': 'username',
'ips_password': 'password',
'signin_options': 'submit',
'redirect':'index.php?'
}
r = session.post(URL, data=login_data)
# Try accessing a page that requires you to be logged in
q = session.get('http://fans.heat.nba.com/community/index.php?app=members&module=messaging§ion=view&do=showConversation&topicID=4314&st=20#msg26627')
print(session.cookies)
print(r.status_code)
print(q.status_code)
if __name__ == '__main__':
main()
URL 是论坛的登录页面。使用“q”变量, session 会尝试访问论坛(私有(private)信使)上的某个网页,只有在您登录后才能访问该网页。但是,该请求的状态代码返回“403”,这意味着我无法成功登录。
为什么我无法登录?在'login_data'中,'ips_username'和'ips_password'是HTML格式。但是,我相信我有错误的实际登录命令('signin_options','redirect')。
有人可以指导我使用正确的登录命令吗?
最佳答案
auth_key
形式有一个隐藏的输入
<input type='hidden' name='auth_key' value='880ea6a14ea49e853634fbdc5015a024' />
所以你需要解析它并传递给登录页面。 您可以简单地使用 regex
def main():
session = requests.Session()
# Get the source page that contain the auth_key
r = requests.get("http://fans.heat.nba.com/community/index.php?app=core&module=global§ion=login")
# Parse it
auth_key = re.findall("auth_key' value='(.*?)'",r.text)[0]
# This is the form data that the page sends when logging in
login_data = {
'ips_username': 'username',
'ips_password': 'password',
'auth_key' : auth_key
}
其余的应该是一样的。
关于python - 使用 Python Requests 登录论坛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31840232/