为什么我无法使用 aiohttp 发出 get-request:期望值:第 1 行第 1 列(字符 0)?

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

为什么我看到错误

向以下机构提出请求时出错 https://data.similarweb.com/api/v1/data?domain=httpbin.org:期待 值:第 1 行第 1 列(字符 0)

with

aiohttp
while
requests.get
返回正确的 json?

import aiohttp
import asyncio
import nest_asyncio

nest_asyncio.apply()

async def fetch(session, url):
    try:
        async with session.get(url, headers=headers) as response:
            return await response.json(content_type=None)
    except Exception as e:
        print(f"Error while making request to {url}: {str(e)}")

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            tasks.append(fetch(session, url))
        responses = await asyncio.gather(*tasks, return_exceptions=True)
        return responses

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
}

urls = ['https://data.similarweb.com/api/v1/data?domain=' + 'httpbin.org']

responses = asyncio.run(fetch_all(urls))

httpbin.org/headers
返回完全相同的标头,唯一的区别在于
X-Amzn-Trace-Id
值。

python-3.x python-asyncio aiohttp get-request
1个回答
0
投票

错误不会在发出请求时发生(正如您的代码错误地假设的那样),而是在请求完成之后发生。您应该检查响应对象,而不是假设一切顺利并处理有效负载。例如,打印出这样的响应状态:

    try:
         async with session.get(url, headers=headers) as response:
             print(response.status, response.reason)
             return await response.json(content_type=None)

你会看到:

403 Forbidden
Error while making request to https://data.similarweb.com/api/v1/data?domain=httpbin.org: Expecting value: line 1 column 1 (char 0)

也就是说,请求失败,并且不包含任何可以解析为 JSON 的有效负载。该错误实际上来自 JSON 模块,而不是来自 aiohttp。

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