【问题标题】:Getting an empty response when fetching data using aiohttp使用 aiohttp 获取数据时得到一个空响应
【发布时间】:2021-06-18 23:54:54
【问题描述】:

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

【问题讨论】:

    标签: python python-requests python-asyncio aiohttp


    【解决方案1】:

    我可以通过在标题中指定 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()
    
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2011-01-31
      • 2020-04-27
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多