开发者

Python - Saving an image from a url [duplicate]

开发者 https://www.devze.com 2023-01-27 03:40 出处:网络
This question already has answers here: 开发者_如何学JAVA Downloading a picture via urllib and python
This question already has answers here: 开发者_如何学JAVA Downloading a picture via urllib and python (20 answers) Closed 7 years ago.

Is there a way to save a picture from a url using urllib or Beautiful Soup?

-Thanks


You want urllib.urlretrieve().


no need of Beautiful Soup as i assume you need to read a binary file. Just read the stream and store it as a file.

import urllib                                       
url = "http://example.com/file.pdf"
uopen = urllib.urlopen(url)
stream = uopen.read()
file = open('filename','w')
file.write(stream)
file.close()

btw. to address the issue of multigigabit images

import urllib
urllib.urlretrieve('url', 'filename')

2nd code snippet gonna be more reliable.. thanks to Ignacio Vazquez-Abrams enlighten this issue of large files.


Just wrote this for myself.

def get_file(url):
    file_temp = NamedTemporaryFile()
    file_temp.write(urllib2.urlopen(url).read())
    file_temp.flush()
    return File(file_temp)


Simply write to a file while reading the data.

from urllib.request import urlopen

local_file_name = 'localfile.txt'
remote_url = 'http://localhost/example'

remote_file = urlopen(remote_url)
local_file = open(file_name, "w")
local_file.write(remote_file.read())
local_file.close()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号