You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chilkat2-Python HTTP表单认证问题:转换请求后返回403 Forbidden

TradingView登录请求:Requests转Chilkat2后返回403 Forbidden

原Requests实现代码

import requests

data = {"username": "user","password": "pass","remember": "on"}

sign_in_url = 'https://www.tradingview.com/accounts/signin/'
signin_headers = {'Referer': 'https://www.tradingview.com'}

response = requests.post(url=sign_in_url, data=data, headers=signin_headers)
token = response.json()['user']['auth_token']

注:凭证错误时,原请求返回状态码200,响应内容:b'{"error":"Invalid username or password","code":"invalid_credentials"}'

问题代码(Chilkat2实现,返回403 Forbidden)

http = chilkat2.Http()
req = chilkat2.HttpRequest()
req.AddParam("username","user")
req.AddParam("password","pass")
req.AddParam("remember","on")
req.Path = '/accounts/signin/'

req.HttpVerb = "POST"
http.FollowRedirects = True

http.SendCookies = True
http.SaveCookies = True
http.CookieDir = "memory"


resp = http.SynchronousRequest('www.tradingview.com',443,True,req)
print(http.LastErrorText)

错误原因及修复方案

返回403的核心原因是缺少原Requests代码中设置的Referer请求头,TradingView服务器会验证请求来源,无Referer的请求会被判定为非法。

修复步骤:

  • 给Chilkat2的HttpRequest添加Referer头,与原Requests保持一致
  • 确认请求的Content-Type匹配(Chilkat2添加表单参数后会自动设置为application/x-www-form-urlencoded,和Requests默认行为一致,无需额外修改)

修复后的完整代码:

http = chilkat2.Http()
req = chilkat2.HttpRequest()

# 添加表单参数
req.AddParam("username","user")
req.AddParam("password","pass")
req.AddParam("remember","on")

# 设置请求路径与方法
req.Path = '/accounts/signin/'
req.HttpVerb = "POST"

# 关键:添加Referer头
req.AddHeader("Referer", "https://www.tradingview.com")

# 保持Cookie相关配置
http.FollowRedirects = True
http.SendCookies = True
http.SaveCookies = True
http.CookieDir = "memory"

resp = http.SynchronousRequest('www.tradingview.com',443,True,req)
# 输出响应内容查看结果
if resp is not None:
    print(resp.BodyStr)
else:
    print(http.LastErrorText)

额外提示:

若添加Referer后仍出现异常,可以补充设置User-Agent头模拟浏览器请求,示例:

req.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")

修复后即使凭证错误,也会返回与原Requests一致的200状态码及错误响应,而非403。

内容的提问来源于stack exchange,提问作者IlyaK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:45:39