python - 在python中异步获取和存储图像

标签 python urllib python-requests

下面的代码是一个非异步代码的例子,请问有什么方法可以异步获取图片吗?

import urllib
for x in range(0,10):
        urllib.urlretrieve("http://test.com/file %s.png" % (x), "temp/file %s.png" % (x))

我也看到了 Grequests库,但如果可能的话,或者如何从文档中做到这一点,我想不通。

最佳答案

您不需要任何第三方库。只需为每个请求创建一个线程,启动线程,然后等待所有线程在后台完成,或者在下载图像时继续您的应用程序。

import threading

results = []
def getter(url, dest):
   results.append(urllib.urlretreave(url, dest))

threads = []
for x in range(0,10):
    t = threading.Thread(target=getter, args=('http://test.com/file %s.png' % x,
                                              'temp/file %s.png' % x))
    t.start()
    threads.append(t)
# wait for all threads to finish
# You can continue doing whatever you want and
# join the threads when you finally need the results.
# They will fatch your urls in the background without
# blocking your main application.
map(lambda t: t.join(), threads)

您可以选择创建一个线程池,从队列中获取 urlsdests

如果您使用的是 Python 3,它已经在 futures 中为您实现了模块。

关于python - 在python中异步获取和存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377475/

相关文章:

python - 使用 urllib(2) 获取和放置 json 数据格式的请求

python - urllib.urlopen() 如何工作?

python - 单元测试 python 请求?

python - 非泛型类型的不同运行时行为

python - 神圣的,python - ex.config 在一个文件和 ex 中

Python:如何获取 URL 的内容类型?

javascript - Google App Engine,使用 Jquery 和 Python 提供文件,返回 2 个相同的文件而不是 1 个

python - 如何在 Python 应用程序中处理 HTTP 状态代码?

python - 每次运行 python 脚本时如何用新结果更新 google 表?

python - 如何使用 tkinter 使用网格函数显示不同的图像?