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



我正在尝试从梦幻英超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())

我能够通过在标头中指定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()

最新更新