如何从这样的链接下载文件?

问题描述

我想问一下如何使用Python从这样的链接中下载文件,我在堆栈中爬了一段时间,没有找到任何有效的方法

我有一个文件链接,如下所示:

https://w3.google.com/tools/cio/forms/anon/org/contentload?content=https://w3.ibm.com/tools/cio/forms/secure/org/data/f48f2294-495b-48f5-8d4e-e418f4b25a48/F_Form1/attachment/bba4ddfd-837d-47a6-87ef-2114f6b3da08链接无效,仅向您显示外观)

在单击它之后,它将打开浏览器并开始打开文件

enter image description here

我不知道文件的命名方式或文件的格式,我只有一个链接到该图像的URL。

我尝试过:

def Download(link):
    r = requests.get(link)
    with open('filename.docx','wb') as f:
        f.write(r.content)

但这绝对不起作用,正如您所看到的,我手动输入文件名是因为它拼命,但它也不起作用,它只能生成1kb的文件,而且里面什么也没有。

我不知道该如何编码才能从这样的链接自动下载?你能帮忙吗?

解决方法

使用urlretrieve中的urllib。参见here

,

您可以使用urllib.request.urlretrieve来获取文件的内容。

示例:

import urllib.request
with open('filename.docx','wb') as f:
    f.write(urllib.request.urlretrieve("https://w3.google.com/tools/cio/forms/anon/org/contentload?content=https://w3.ibm.com/tools/cio/forms/secure/org/data/f48f2294-495b-48f5-8d4e-e418f4b25a48/F_Form1/attachment/bba4ddfd-837d-47a6-87ef-2114f6b3da08"))