有没有办法使用“请求”模块下载多个文件

2024-10-04 01:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个名为hdrihaven.com的网站下载多个.hdr文件。 我对python的了解不是很好,但以下是我迄今为止尝试过的内容:

import requests

url = 'https://hdrihaven.com/files/hdris/'
resolution = '4k'
file = 'pump_station' #would need to be every file

url_2k = url + file + '_' + resolution + '.hdr'
print(url_2k)

r = requests.get(url_2k, allow_redirects=True)
open(file + resolution + '.hdr', 'wb').write(r.content)

理想情况下file只需在目录中的每个文件上循环

提前感谢您的回答

编辑

我在github上找到了一个脚本,它可以满足我的需要:https://github.com/Alzy/hdrihaven_dl。我在这里编辑它以满足我的需要:https://github.com/ktkk/hdrihaven-downloader。它使用的技术是,按照评论中的建议,循环浏览所有可用文件的列表

我发现请求模块和urllib比从Chrome上下载本机的速度要慢得多。如果有人对我如何加快这些有想法,请让我知道


Tags: 文件httpsimportgithubcomurl编辑内容
1条回答
网友
1楼 · 发布于 2024-10-04 01:23:56

有两种方法可以做到这一点:

  1. 您可以使用URL获取所有文件,并通过循环进行迭代以分别下载它们。当然,这只有在存在这样一个URL的情况下才有效

  2. 您可以将单个URL传递给可以并行/批量下载它们的函数

例如:

import os
import requests
from time import time
from multiprocessing.pool import ThreadPool

def url_response(url):
    path, url = url
    r = requests.get(url, stream = True)
    with open(path, 'wb') as f:
        for ch in r:
            f.write(ch)

urls = [("Event1", "https://www.python.org/events/python-events/805/"),("Event2", "https://www.python.org/events/python-events/801/"),
("Event3", "https://www.python.org/events/python-user-group/816/")]


start = time()

for x in urls:
    url_response (x)
print(f"Time to download: {time() - start}")

此代码段取自此处Download multiple files (Parallel/bulk download)。请继续阅读,了解更多有关如何做到这一点的信息

相关问题 更多 >