使用 aiohttp 获取数据时获得空响应

时间:2021-06-18 23:54:54

标签: python python-requests python-asyncio aiohttp

我正在尝试从 Fantasy Premier League API 获取一些数据。在 python 中使用 requests 库非常简单。 [片段 1]

但是,当尝试使用 asyncioaiohttp 获取相同的数据时,即使状态为 200,我也得到了一个空响应。有人能告诉我我遗漏了什么吗?

>

我能够使用 aiohttp 从私有 API 获取 json 数据。所以,看起来我的配置没有问题。

我使用的是 python 3.7.9。

使用请求

import requests
response = requests.get("https://fantasy.premierleague.com/api/bootstrap-static/")
response.json()

使用 asyncio 和 aiohttp

import aiohttp
import asyncio
async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://fantasy.premierleague.com/api/bootstrap-static/') as resp:
            return await resp.json()

asyncio.run(main())

1 个答案:

答案 0 :(得分:0)

我能够通过在标头中指定 User-Agent 来解决这个问题。

headers = {'User-Agent': 'xyz'}
async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(
            'https://fantasy.premierleague.com/api/bootstrap-static/',
            headers=headers
        ) as resp:
            return await resp.json()

await main()