从 thetvdb.com 访问 API v2 时出错 [Python 请求。错误 403]

zap*_*pen 5 python post python-requests

我正在尝试从thetvdb.com访问 API v2 。不幸的是我总是收到 403 错误。

这是我所拥有的:

#!/usr/bin/python3
import requests

url = "https://api.thetvdb.com/login"
headers = {'content-type': 'application/json'}
payload = {"apikey":"123","username":"secretusername","userkey":"123"}
post = requests.post(url, data = payload, headers = headers)
print(post.status_code, post.reason)
Run Code Online (Sandbox Code Playgroud)

根据 API 文档,我必须进行身份验证才能获取令牌。但我刚刚得到 403 Forbidden。

现在我尝试使用curl:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: 
application/json' -d  
{"apikey":"123","username":"secretusername","userkey":"123"}' 
'https://api.thetvdb.com/login'
Run Code Online (Sandbox Code Playgroud)

这非常有效。谁能解释一下我缺少什么?这让我发疯。

我也尝试过

post = requests.post(url, data = json.dumps(payload), headers = headers)
Run Code Online (Sandbox Code Playgroud)

同样的错误。

Sar*_*lai 4

您必须explicitly将其转换payload为 json 字符串并作为 传递data。看来您已经完成了,您也可以尝试将用户代理设置为curl/7.47.1

headers = {'content-type': 'application/json', 'User-Agent': 'curl/7.47.1'}
post = requests.post(url, data = json.dumps(payload), headers = headers)
Run Code Online (Sandbox Code Playgroud)

该程序看起来像

#!/usr/bin/python3
import requests
import json    

url = "https://api.thetvdb.com/login"
headers = {'content-type': 'application/json', 'User-Agent': 'curl/7.47.1'}
payload = {"apikey":"123","username":"secretusername","userkey":"123"}
post = requests.post(url, data = json.dumps(payload), headers = headers)
print(post.status_code, post.reason)
Run Code Online (Sandbox Code Playgroud)