[io.Text IO包装的python aiohttp客户端响应对象

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

我一直在摸索我的代码的问题,我想使用一个库来打开网页的内容并以特定的方式查看它们,在查看该lib的源代码后,我发现要使用此库lib,我需要使用_io.TextIOWrapper对象而不是aiohttp对象,因此我想知道是否有任何方法也可以转换。这里是一些例子

>>> open('./NEWS.txt')
<_io.TextIOWrapper name='./NEWS.txt' mode='r' encoding='cp1252'>
>>> import aiohttp
>>> import asyncio
>>> async def fetch(session, url):
...     async with session.get(url) as response:
...         return response
...
>>> async def main():
...     async with aiohttp.ClientSession() as session:
...         html = await fetch(session, 'http://python.org')
...         print(html)
...
>>> if __name__ == '__main__':
...     loop = asyncio.get_event_loop()
...     loop.run_until_complete(main())
...
<ClientResponse(https://www.python.org/) [200 OK]>
<CIMultiDictProxy('Server': 'nginx', 'Content-Type': 'text/html; charset=utf-8', 'X-Frame-Options': 'DENY', 'Via': '1.1 vegur', 'Via': '1.1 varnish', 'Content-Length': '49058', 'Accept-Ranges': 'bytes', 'Date': 'Fri, 08 May 2020 14:20:23 GMT', 'Via': '1.1 varnish', 'Age': '1960', 'Connection': 'keep-alive', 'X-Served-By': 'cache-bwi5137-BWI, cache-pao17432-PAO', 'X-Cache': 'HIT, HIT', 'X-Cache-Hits': '2, 2', 'X-Timer': 'S1588947623.222259,VS0,VE0', 'Vary': 'Cookie', 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains')>

>>>


有什么想法吗?请让我知道

python aiohttp
1个回答
0
投票

TextIOWrapper将字节流作为第一个参数。由于您的响应只是一个字符串,因此您可以将字符串转换为字节流,然后将其传递给TextIOWrapper。

import io

html = '<html></html>'
byteStream = io.BufferedReader(io.BytesIO(html.encode("utf-8")))
textWrapper = io.TextIOWrapper(byteStream)
print(textWrapper.read())
© www.soinside.com 2019 - 2024. All rights reserved.