【问题标题】:Python requests post: data and jsonPython请求post:数据和json
【发布时间】:2022-07-27 14:48:28
【问题描述】:

多年来,我使用以下 Python 代码成功检索了登录页面后面的网页:

username = 'user'
password = 'pass'
login_url = 'https://company.com/login?url='
redirect_url = 'https://epaper.company.com/'
data = { 'email' : username, 'pass' : password }

initial_url = login_url + quote(redirect_url)
response = requests.post(initial_url, data=data)

然后在大约 2 个月前 company.com 发生了一些变化,请求返回状态码 400。我尝试将数据参数更改为 json (response = requests.post(initial_url, json=data)),这给了我一个 200 响应,告诉我提供了错误的密码。

有什么我可以尝试调试的想法吗?

谢谢, 一月

更新:我刚刚尝试使用请求会话从登录页面检索 csrf_token(建议 here),所以现在我的代码如下:

with requests.Session() as sess:
    response = sess.get(login_url)
    signin = BeautifulSoup(response._content, 'html.parser')
    data['csrf_token'] = signin.find('input', {'name':'csrf_token'})['value']
    response = sess.post(initial_url, data=data)

不幸的是,响应仍然是 400(和 200/json 参数的密码错误)。

【问题讨论】:

    标签: python-requests


    【解决方案1】:

    首先。 当你发送data=data时,使用了{"Content-Type":"application/x-www-form-urlencoded"}; 如果您发送 json=data,则应在标头响应中使用 {"Content-Type":"application/json"}

    其次。 也许已经添加了重定向。 尝试添加:

    response = sess.post(url, data=data)
    print("URL you expect", url)
    print("Last request URL:", response.url)
    

    一定要检查:

    print(sess.cookies.get_dict())
    print(response.headers)
    

    如果检查时出现意外结果,请按如下方式更改代码:

    response = sess.post(url, data=data, allow_redirects=False)
    

    我希望这对那些面临同样错误的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 2013-12-23
      • 1970-01-01
      • 2013-06-29
      相关资源
      最近更新 更多