What command to use instead of urllib.request.urlretrieve?

与世无争的帅哥 提交于 2019-12-03 11:02:39

问题


I'm currently writing a script that downloads a file from a URL

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

According to the docs, urllib.request.urlretrieve is a legacy interface and might become deprecated, therefore I would like to avoid it so I don't have to rewrite this code in the near future.

I'm unable to find another interface like download(url, filename) in standard libraries. If urlretrieve is considered a legacy interface in Python 3, what is the replacement?


回答1:


Deprecated is one thing, might become deprecated at some point in the future is another.

If it suits your needs, I'd continuing using urlretrieve.

That said, you can do without it:

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)



回答2:


requests is really nice for this. There are a few dependencies though to install it. Here is an example.

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



回答3:


Another solution without the use of shutil and no other external libraries like 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)


来源:https://stackoverflow.com/questions/15035123/what-command-to-use-instead-of-urllib-request-urlretrieve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!