python 通过url列表批量下载到指定位置
时间: 2024-01-21 14:03:56 浏览: 25
好的,您可以通过以下步骤来实现Python批量下载URL列表中的文件到指定位置:
1. 指定下载路径:定义一个变量来指定下载路径。例如,将下载路径保存在`download_path`变量中。
2. 读取URL列表:将URL列表保存在一个文本文件中,每个URL一行。例如,将URL列表保存在`urls.txt`文件中。
3. 使用Python的requests库:使用requests库发送HTTP请求并下载文件。
4. 循环遍历URL列表并下载文件:使用Python的for循环语句来遍历URL列表中的每个URL,并下载对应的文件到指定路径。
下面是一个示例代码:
```python
import requests
import os
# 指定下载路径
download_path = '/path/to/download/'
# 读取URL列表
with open('urls.txt') as f:
urls = f.readlines()
# 使用requests库下载文件
for url in urls:
url = url.strip()
filename = url.split('/')[-1] # 使用URL中的文件名作为本地文件名
local_filepath = os.path.join(download_path, filename)
try:
response = requests.get(url, stream=True)
with open(local_filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print(f"{filename} 下载成功!")
except Exception as e:
print(f"{filename} 下载失败:{e}")
```
需要注意的是,上述代码中使用了os库的`join`函数来构建本地文件路径,同时也处理了下载失败的情况并打印了错误信息。