python - 使用 Python Requests 登录论坛

标签 python python-3.x python-requests

我正在尝试使用 python 请求登录论坛。这是我要登录的论坛:http://fans.heat.nba.com/community/

这是我的代码:

import requests
import sys

URL = "http://fans.heat.nba.com/community/index.php?app=core&module=global&section=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&section=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&section=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/

相关文章:

python - 正在寻找函数语法来根据两个不同的字典键/值对检查数据帧列?

python - Django.core.exceptions.ImproperlyConfigured : AUTH_USER_MODEL refers to model %s that has not been installed

python3操作系统错误: [Errno 107] Transport endpoint is not connected

python - 站点地图中的优先级问题

python - 仅打印 .csv 文件中的某些行

python - 请求库在 Python 2 和 Python 3 上崩溃

python - http响应返回的json对象

Python 请求未返回与浏览器请求/cURL 相同的 header

python - 在 Python3 的 Matplotlib 的极坐标/径向条形图中获取条形图顶部的标签

python - 为什么不将 if __name__ == '__main__' 放在模块的开头?