【问题标题】:Download a file with urllib and specify where to save it使用 urllib 下载文件并指定保存位置
【发布时间】:2020-01-16 02:40:45
【问题描述】:

我想在 python 中使用 urllib 下载一个“.exe”文件。这是我到目前为止在互联网上找到的代码:

from urllib import request

url = "https://example.com"
download_file_name = "example.exe"

def download(url, download_file_name):

    urllib.request.urlretrieve(url, download_file_name)

download(url, download_file_name)

我收到一个错误,“NameError: name 'urllib' is not defined”。 urllib导入了为什么还是报错?

另外,我可以在下载后更改/指定 .exe 的保存位置吗?

【问题讨论】:

    标签: python-3.x urllib


    【解决方案1】:

    您没有导入urllib。您从 urllib 导入了名称 request。您可以通过提供download_file_name 的完整路径来指定文件的保存位置。

    试试这个:

    from urllib import request
    
    url = "https://example.com"
    download_file_name = "C:\\example.exe"
    
    def download(url, download_file_name):
        request.urlretrieve(url, download_file_name)
    
    download(url, download_file_name)
    

    然而,urlretrieve 的全部意义在于下载一个临时文件。它被保存在一个临时位置并最终被删除。你可以通过查看request.urlretrieve的结果来发现它的保存位置:

    url = "https://example.com"
    tmp_file = request.urlretrieve(url)
    print("Temporary file was saved at " + tmp_file)
    

    【讨论】:

    • 非常感谢,有机会将其下载为永久文件吗? python中是否存在这种方法?
    • 你可以改用urlopen
    • urlopen() 也下载文件?这个名字比较混乱。我不需要在 urlopen() 之后添加 read() 方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2011-06-13
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多