使用什么命令而不是urllib.request.urlretrieve?

时间:2013-02-22 23:42:28

标签: python python-3.x python-requests urllib

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

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

根据文档,urllib.request.urlretrieve是遗留接口,可能会被弃用,因此我想避免使用它,因此我不必在不久的将来重写此代码。

我无法在标准库中找到像download(url, filename)这样的其他界面。如果{3}被认为是Python 3中的遗留接口,那么替换是什么?

3 个答案:

答案 0 :(得分:20)

不推荐是一回事,可能会在将来的某个时候被弃用是另一回事。

如果符合您的需求,我会继续使用urlretrieve

那就是说,你可以不用它:

from urllib.request import urlopen
from shutil import copyfileobj

with urlopen(image['url']) as in_stream, open(p, 'wb') as out_file:
    copyfileobj(in_stream, out_file)

答案 1 :(得分:16)

请求对此非常好。虽然安装它但有几个依赖项。这是一个例子。

import requests
r = requests.get('imgurl')
with open('pic.jpg','wb') as f:
  f.write(r.content)

答案 2 :(得分:0)

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

import urllib.request

image = {'url': 'https://cdn.sstatic.net/Sites/stackoverflow/img/appletouch-icon.png'}
p = 'image.png'

response = urllib.request.urlopen(image['url'])
image = response.read()

file = open(p, 'wb')

file.write(image)
file.close()