aiohttp 中 request.iter_content() 的等效方法是什么?

Yap*_*atS 5 web-scraping python-3.x python-requests python-asyncio aiohttp

我正在编写一个小型网络抓取工具,它可以从特定站点获取大量图像。但是,IO 速度很慢,所以我用 google 搜索并找到了 asyncio 和 aiohttp 来处理 IO 绑定操作开销。我梳理了 aiohttp 文档,但在请求模块中找不到任何看起来像 iter_content() 替代方法的函数。我需要它将图像数据写入磁盘。任何人都可以帮忙吗?

Jas*_*ohi 5

您应该使用该ClientResponse.content属性。它是一个StreamReader实例,可用于增量读取响应。从文档

with open(filename, 'wb') as fd:
    while True:
        chunk = await r.content.read(chunk_size)
        if not chunk:
            break
        fd.write(chunk)
Run Code Online (Sandbox Code Playgroud)

StreamReader还支持异步迭代:

async for line in r.content:
    ...
async for chunk in r.content.iter_chunked(1024):
    ...
async for slice in r.content.iter_any(): # as much as possible before blocking
    ...
Run Code Online (Sandbox Code Playgroud)