Python 有效地从 URL 下载图片

3

我是一名有用的助手,可以为您提供文字翻译。以下是需要翻译的内容:

我有一个存储在Pandas数据框中的图像URL列表。我希望下载所有这些图像并将它们存储在本地。

我用来实现此操作的代码如下:

import os
import requests

def load(df, output_folder):        
    print("Ready to load "+str(len(df.index))+" images.")
    for i,row in df.iterrows():
        print("Image "+str(i))
        save_image_from_url(row["image_url"], os.path.join(output_folder, row["image_name"]))

''' From a given URL, download the image and store it at the given path'''
def save_image_from_url(url, output_path):
    image = requests.get(url)

    with open(output_path, 'wb') as f:
        f.write(image.content)

问题在于该过程速度非常缓慢(每张图片需要0.5秒至4秒)。是否有更快的方法?

这取决于您下载图像的服务器。如果服务器本身很慢,那么您无能为力。 - bigbounty
1
如果您的图像服务器足够快(很可能是),那么尝试并行下载。 - rdas
1个回答

5

显而易见的方法是并行下载,你可以在文档中找到一个清晰的例子。

对于你的情况,尝试这种方法:

import concurrent.futures
import os
import requests


def save_image_from_url(url, output_folder):
    image = requests.get(url.image_url)
    output_path = os.path.join(
        output_folder, url.image_name
    )
    with open(output_path, "wb") as f:
        f.write(image.content)

def load(df, output_folder):    
    with concurrent.futures.ThreadPoolExecutor(
        max_workers=5
    ) as executor:
        future_to_url = {
            executor.submit(save_image_from_url, url, output_folder): url
            for _, url in df.iterrows()
        }
        for future in concurrent.futures.as_completed(
            future_to_url
        ):
            url = future_to_url[future]
            try:
                future.result()
            except Exception as exc:
                print(
                    "%r generated an exception: %s" % (url, exc)
                )

1
它运行良好。我的图像以每秒120Mbps的速度下载,我认为我无法做得更好了。谢谢。 - Nakeuh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接