28

我目前正在编写一个从 URL 下载文件的脚本

import urllib.request
urllib.request.urlretrieve(my_url, 'my_filename')

文档urllib.request.urlretrieve状态:

以下函数和类是从 Python 2 模块 urllib(与 urllib2 相对)移植而来的。它们可能会在未来的某个时候被弃用。

因此我想避免它,所以我不必在不久的将来重写这段代码。

我无法download(url, filename)在标准库中找到另一个接口。如果urlretrieve被认为是 Python 3 中的遗留接口,那么替换是什么?

4

4 回答 4

26

不推荐使用是一回事,将来可能会被弃用另一回事。

如果它适合您的需求,我会继续使用urlretrieve.

也就是说,你可以没有它:

from urllib.request import urlopen
from shutil import copyfileobj

with urlopen(my_url) as in_stream, open('my_filename', 'wb') as out_file:
    copyfileobj(in_stream, out_file)
于 2013-02-23T00:22:12.080 回答
25

requests 非常适合这个。虽然安装它有一些依赖项。这是一个例子。

import requests
r = requests.get('imgurl')
with open('pic.jpg','wb') as f:
  f.write(r.content)
于 2013-02-22T23:51:05.090 回答
1

另一种不使用shutil也没有其他外部库的解决方案,如requests.

import urllib.request

image_url = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png"
response = urllib.request.urlopen(image_url)
image = response.read()

with open("image.png", "wb") as file:
    file.write(image)
于 2018-01-28T04:41:20.357 回答
0

不确定这是否是您正在寻找的,或者是否有“更好”的方式,但这是我在库之后添加到脚本顶部的内容,以使我的脚本与 Python 2/3 兼容。

# Python version compatibility
if version.major == 3:
    from urllib.error import HTTPError
    from urllib.request import urlopen, urlretrieve

elif version.major == 2:
    from urllib2 import HTTPError, urlopen

    def urlretrieve(url, data):
        url_data = urlopen(url)
        with open(data, "wb") as local_file:
            local_file.write(url_data.read())
else:
    raise ValueError('No valid Python interpreter found.')

这至少看起来像是一个方便的技巧,我希望这可能对某人有所帮助。

最好的!

于 2021-08-21T04:42:21.973 回答