当前位置: 代码迷 >> python >> 如何使用龙卷风获取图像并将其写入文件?
  详细解决方案

如何使用龙卷风获取图像并将其写入文件?

热度:95   发布时间:2023-07-16 10:40:25.0

我有一个网址:“ ”

我想获取图像并将其写入文件,我将代码编写如下:

import urllib.request
web = urllib.request.urlopen(iturl)
itdata = web.read()
f = open(str(cou) + '.png', "wb")
cou = cou + 1
f.write(itdata)
f.close()

我的问题是,如果我要下载许多网址,如何通过龙卷风协程实现它?

这不是完整的代码,只是我在5分钟内想到的东西,但它应该为您提供足够的信息以满足您的要求。 如果您有任何疑问或需要进一步的解释,请告诉我。

from tornado import gen, httpclient, ioloop

@gen.coroutine
def main():
    client = httpclient.AsyncHTTPClient()
    response = yield client.fetch(
        'https://findicons.com/files/icons/2787/beautiful_flat_icons/128/running.png',
        download_image,
        follow_redirects = True)

@gen.coroutine
def download_image(response):
    buffer_size = 1024
    filename = response.request.url.split('/')[-1]  # this is not always reliable
    with open(filename, 'ab') as img:
        while True:
            chunk = response.buffer.read(buffer_size)
            if chunk == '':
                break
            img.write(chunk)
            yield

ioloop.IOLoop.current().run_sync(main)

参考

  相关解决方案