我正在尝试使用两种不同的方法在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 没有超时有什么想法吗?我在这里缺少什么?
aiohttp 超时但 requests 却没有超时的原因可能有很多。最突出的是它们各自处理 DNS 解析的方式以及它们使用事件循环的方式。根据我的经验,请求更可靠。