【问题标题】:What is the equivalent method of request.iter_content() in aiohttp?aiohttp中request.iter_content()的等效方法是什么?
【发布时间】:2016-01-26 15:34:15
【问题描述】:

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

【问题讨论】:

    标签: python-3.x web-scraping python-requests python-asyncio aiohttp


    【解决方案1】:

    您应该使用ClientResponse.content 属性。这是一个StreamReader 实例,可用于增量读取响应。来自docs

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

    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
        ...
    

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多