有人能解释为什么python aiohttp返回的响应内容比请求。明白吗?

2024-05-17 03:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我正在研究python aiohttp库,并将其与python请求进行比较。代码如下:

import aiohttp
import asyncio
import requests

request_url = 'http://www.baidu.com'
requests_resp = requests.get(request_url)

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        aio_resp = await fetch(session, request_url)
        print('aio_resp_length =', len(aio_resp))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

print('requests_resp_length = ', len(requests_resp.text))

响应长度差异很大

aio_resp_length = 152576
requests_resp_length =  2381

不知道接下来会发生什么aiohttp.session.get获取,但这个结果并不总是这样。当您将请求的url更改为http://www.example.com时 响应长度相同。有人能告诉我这里发生了什么事吗?你知道吗

干杯


Tags: importloopasynciohttpurlgetasyncaiohttp
1条回答
网友
1楼 · 发布于 2024-05-17 03:19:21

因为aiohttp的响应中有换行符,而请求没有

你可以这样检查他们的反应

print('requests_resp_length = ', requests_resp.text[0:100])

print('aio_resp_length =', aio_resp[0:100])

相关问题 更多 >