4

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

-Thanks

fredley
  • 32,953
  • 42
  • 145
  • 236
user377419
  • 4,681
  • 13
  • 42
  • 56

4 Answers4

5

You want urllib.urlretrieve().

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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.

unmounted
  • 33,530
  • 16
  • 61
  • 61
Shiv Deepak
  • 3,122
  • 5
  • 34
  • 49
0

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)
bdd
  • 3,436
  • 5
  • 31
  • 43
-1

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()
Dahlgren
  • 781
  • 4
  • 13