在Python中使用请求下载多个文件 [英] Downloading multiple files with requests in Python

查看:58
本文介绍了在Python中使用请求下载多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我面临以下问题:

我在列表中有3个下载链接.仅列表中的最后一个文件被完全下载.其他文件的大小为1 KB.

I have 3 download links in a list. Only the last file in the list is downloaded completely. The others have a file size of one kilobyte.

代码:

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)

结果如下:

结果

如何确保所有文件都正确下载?所有链接都是直接下载链接.

How do I make sure that all files are downloaded correctly? All links are direct download links.

提前谢谢!

我发现只有在读取.txt中的链接时才会发生

I discovered it only happens when I read the links from the .txt

如果我这样在p​​ython中创建列表:

If I create the list in python like this:

links = ["http://ipv4.download.thinkbroadband.com/20MB.zip",
            "http://ipv4.download.thinkbroadband.com/10MB.zip",
            "http://ipv4.download.thinkbroadband.com/5MB.zip"]

...问题没有出现.

... the problem doesnt appear.

可复制的示例:

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的内容:

content of links.txt:

http://ipv4.download.thinkbroadband.com/20MB.zip
http://ipv4.download.thinkbroadband.com/10MB.zip
http://ipv4.download.thinkbroadband.com/5MB.zip

推荐答案

url = url.replace("\ n",")

url = url.replace("\n", "")

解决了!

这篇关于在Python中使用请求下载多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆