aiohttp 存在超时问题,但请求没有超时问题

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

我正在尝试使用两种不同的方法在Python中获取网页:

requests
aiohttp
。 requests 方法工作正常,但 aiohttp 方法会导致超时。这是代码:

import asyncio
import aiohttp
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
    "X-Requested-With": "XMLHttpRequest",
    "Cookie": ""
}

url = "an_url"

async def request_requests():
    print("Requesting...")
    try:
        response = requests.get(url, headers=headers, timeout=3)
        print(response.text)
    except requests.exceptions.ReadTimeout:
        print("Timeout REQUESTS")


async def request_aiohttp():
    print("Requesting...")
    try:
        async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=3)) as session:
            async with session.get(url) as response:
                print(await response.text())
    except asyncio.TimeoutError:
        print("Timeout AIOHTTP")

if __name__ == '__main__':
    asyncio.run(request_requests())
    asyncio.run(request_aiohttp())

当我运行脚本时,

requests
成功检索数据,但
aiohttp
始终超时。两种方法都设置了 3 秒超时。

有趣的是,此问题发生在我正在使用的特定 URL 上。对于大多数其他 URL,

requests
aiohttp
都可以按预期工作。

关于为什么 aiohttp 超时而 requests 没有超时有什么想法吗?我在这里缺少什么?

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

aiohttp 超时但 requests 却没有超时的原因可能有很多。最突出的是它们各自处理 DNS 解析的方式以及它们使用事件循环的方式。根据我的经验,请求更可靠。

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