使用request库通过python3脚本访问api时出现http403错误,但通过浏览器访问时却没有问题

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

当我尝试访问没有文档且不受官方支持的 API 时遇到问题。

问题是,如果我将 API 链接放入我的各种浏览器中,它可以正常工作,这里有一个链接:api,但是当我尝试通过 python 脚本访问它时,我收到 403 错误。

这是 API https://api.tracker.gg/api/v2/valorant/standard/profile/riot/pyro%23dif/segments/season-report?当我放入 Chrome 浏览器时,它会发回 200 ok 响应。

我假设它不是身份验证或 Cookie/会话数据,因为它通过各种不同的浏览器工作,并且我已经尝试过删除 Cookie 和退出网站等。所有似乎都有效。

我还假设它不是 IP 阻止或速率限制,因为它是一个单一请求,并且来自同一 IP,它似乎工作正常。

不过我可能假设错误。

所以 User-Agent 标头一定是我尝试更改用户代理但没有成功的问题。我尝试更改各种标头数据,使其与我的 Chrome 浏览器相同,但似乎没有任何效果。我一整天都在互联网和堆栈溢出中搜索,但找不到解决方案

我的Python脚本:

import requests, json


playerTag = "pyro%23dif"

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache',
    'Cookie': '__cflb=02DiuFQAkRrzD1P1mdkJhfdTc9AmTWwYjJGtpDcTftSd2; X-Mapping-Server=s7; cf_clearance=I2RZ8gC2GNXzVT0nf_bcKUQEtU5oGRrFq6Eq1OjR_Xs-1696873939-0-1-5622ec48.635f2445.c3629c20-0.2.1696873939',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
}


# API endpoint
api_endpoint_url = f'https://api.tracker.gg/api/v2/valorant/standard/profile/riot/{playerTag}/segments/season-report?'

# Send an HTTP GET request to the API endpoint
response = requests.get(api_endpoint_url, headers=headers) 

if response.status_code == 200:
    data = response.json() 
    hours_display_value = data["stats"]["hours"]["displayValue"]

    print(f"Response code: {response.status_code}")
    print(hours_display_value)
else:
    print(f"{response.status_code} Error: {response.reason}")

预期输出:来自 API 的 PRINTS

hours_display_value

实际输出:403错误:禁止

有谁知道我为什么会收到 403 错误以及如何解决它,以便我可以从 python 脚本访问此 API。如果出现问题,因为我需要对其进行身份验证或有任何共享。

编辑:也许这与 HTTP 和 HTTPS 有关?

python python-requests http-status-code-403
1个回答
0
投票

api.tracker.gg 是什么? 您需要重新检查文档。

对于 Path Of Exile,他们的网站有一个用户代码 POESESSID。这是通过在浏览器中进入开发者模式找到的。

然后在 python 或 lua http 请求的标头中使用它。

我可以建议这里也发生同样的事情吗?

X

© www.soinside.com 2019 - 2024. All rights reserved.