为什么我无法使用Python访问API,但我可以使用浏览器访问?

问题描述 投票:0回答:2

我想使用 Python 访问 API,但它不起作用。我得到这个 JSON 文件:

{"status": 403, "message": "Forbidden"}

我的代码:

result = requests.get(f"https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1").json()
with open("result.json", "w") as f:
    json.dump(result, f)

但是当我在浏览器上访问API时,它可以工作:https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1

python json python-requests
2个回答
0
投票

工作顺利。您必须将用户代理作为标头注入

import requests
import json
headers={'User-Agent':'mozilla/5.0'}
result = requests.get(f"https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1",headers=headers).json()
jdata =  json.dumps(result,indent=4)
with open("result.json", "w") as f:
    f.write(jdata)
   

0
投票

我使用了与您相同的示例,但出现错误 你能告诉我发生了什么吗?

  "message": "The application has encountered an error",
            "type": "NullPointerError"

导入请求 导入 json 导入 urllib.parse

query = "SELECT min({cart_pai.pk}) FROM {cart as carrinho JOIN cart AS cart_pai ON {carrinho.parent} = {cart_pai.pk}}"
safe_string = urllib.parse.quote_plus(query)

headers = {
           'Accept': 'application/json',
           'Authorization': 'Bearer 4DmQkomKs0z845705JIlfW-hhNg'}

result = requests.get(f"https://api.cokecxf-commercec1-p1-public.model-t.cc.commerce.ondemand.com/clarowebservices/v2/claro/flexiblesearch/export/search/getAsCsv?"+safe_string,
                      headers=headers).json()
jdata = json.dumps(result, indent=4)
with open("result.json", "w") as f:
    f.write(jdata)
print(jdata)
© www.soinside.com 2019 - 2024. All rights reserved.