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()
精彩评论