【发布时间】:2020-02-23 17:21:15
【问题描述】:
目前我面临以下问题:
我在一个列表中有 3 个下载链接。只有列表中的最后一个文件被完全下载。 其他的文件大小为 1 KB。
代码:
from requests import get
def download(url, filename):
with open(filename, "wb") as file:
response = get(url, stream=True)
file.write(response.content)
for link in f:
url = link
split_url = url.split("/")
filename = split_url[-1]
filename = filename.replace("\n", "")
download(url,filename)
结果如下:
如何确保正确下载所有文件? 所有链接均为直接下载链接。
提前致谢!
编辑:
我发现只有当我从 .txt 中读取链接时才会发生这种情况
如果我像这样在 python 中创建列表:
links = ["http://ipv4.download.thinkbroadband.com/20MB.zip",
"http://ipv4.download.thinkbroadband.com/10MB.zip",
"http://ipv4.download.thinkbroadband.com/5MB.zip"]
...问题没有出现。
可重现的例子:
from requests import get
def download(url, filename):
with open(filename, "wb") as file:
response = get(url, stream = True)
file.write(response.content)
f = open('links.txt','r')
for link in f:
url = link
split_url = url.split("/")
filename = split_url[-1]
filename = filename.replace("\n", "")
download(url,filename)
links.txt 的内容:
http://ipv4.download.thinkbroadband.com/20MB.zip
http://ipv4.download.thinkbroadband.com/10MB.zip
http://ipv4.download.thinkbroadband.com/5MB.zip
【问题讨论】:
-
在
download打印/检查内容和文件名是否正确? -
你没有尝试的原因this example in the docs
-
这能回答你的问题吗? How to download image using requests
-
1:所有 3 个文件的文件名都是正确的。只有文件 3 的内容是正确的。其他文件似乎是空的 2,3:我试过了,同样的问题 :( 当我切换列表中的链接时,我仍然遇到同样的问题 - 只有最后一个文件被正确下载
标签: python python-3.x download python-requests