从thetvdb.com访问API v2时出错[Python requests.Error 403]

2024-05-21 03:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从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)

根据API文档,为了获得令牌,我必须进行身份验证。但我刚拿到403

现在我尝试使用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'

这一切都很完美。谁能解释一下我遗漏了什么?这快把我逼疯了

我也试过了

post = requests.post(url, data = json.dumps(payload), headers = headers)

同样的错误


Tags: httpscomapijsonurlapplication错误login
3条回答
    url = 'http://169.254.169.254/latest/meta-data/iam/'
    payload = {}
    headers = {'content-type': 'application/json', 'User-Agent': 'curl/7.47.1'}
   #headers = {'content-type': 'application/json'}
   response = requests.post(url, headers=headers, data=payload, 
   verify='/installed/aws/usr/lib/python2.7/site- 
   packages/certifi/cacert.pem', timeout=5)
   instance_profile_role_name = response.text
   print response.text`

您必须explicitlypayload转换为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)

这个程序看起来像

#!/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)

我认为您需要在python请求中传递Accept头。大概是这样的:

header = {
        'Accept' : 'application/json', 
        'Content-Type' : 'application/json'
        "Accept-Encoding": "gzip, deflate, sdch, br",
        "Accept-Language": "en-US,en;q=0.8",
        "User-Agent": "some user-agent",
    }

相关问题 更多 >