微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用请求 python 下载文件

如何解决使用请求 python 下载文件

我有一个作为下载对话框打开的文件的 URL 列表,其中包含保存和打开的选项。 我正在使用 python requests 模块下载文件。在使用 Python IDLE 时,我可以使用以下代码下载文件

link = fileurl
r = requests.get(link,allow_redirects=True)
with open ("a.torrent",'wb') as code:
    code.write(r.content)

但是当我将此代码与 for 循环一起使用时,下载的文件已损坏或说无法打开。

for link in links:
    name = str(links.index(link)) ++ ".torrent"
    r = requests.get(link,allow_redirects=True)
    with open (name,'wb') as code:
        code.write(r.content)

解决方法

正如@Nikolay Patarov 在评论中指出的,您一次又一次地重写同一个文件。要解决此问题,您可以将内容保存在不同的文件中,如下所示:

for i,link in enumerate(links):
    r = requests.get(link,allow_redirects=True)
    with open(f"a{i}.torrent","wb") as code:
        code.write(r.content)
        code.close()

在这里,我只是将所有链接的内容保存在不同的文件中。

,

如果您尝试从网站下载视频,请尝试

r = get(video_link,stream=True)
with open ("a.mp4",'wb') as code:
    for chunk in r.iter_content(chunk_size=1024):
        file.write(chunk)                

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。