写一个python加速下载链接的代码
时间: 2024-02-07 16:02:36 浏览: 63
以下是一个简单的Python脚本,可以使用多线程加速下载链接:
```python
import requests
from multiprocessing.dummy import Pool as ThreadPool
def download(url):
r = requests.get(url, stream=True)
filename = url.split("/")[-1]
with open(filename, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
def multi_download(urls, num_threads=8):
pool = ThreadPool(num_threads)
pool.map(download, urls)
pool.close()
pool.join()
if __name__ == "__main__":
urls = ["https://example.com/file1.zip", "https://example.com/file2.zip", "https://example.com/file3.zip"]
multi_download(urls, num_threads=8)
```
在此示例中,我们使用requests模块下载文件,并使用multiprocessing.dummy模块实现多线程下载。您可以将要下载的链接添加到urls列表中,并设置num_threads参数以指定要使用的线程数。
阅读全文