Retrieve and save an image from a web page

vegaseat 5 Tallied Votes 2K Views Share

Python experiment to get an image from a web page and save it to an image file. Updated code to work with both Python versions ...

'''urlretrieve_image1.py
retrieve and save an image from a web page
using ...
urlretrieve(url[, filename[, reporthook[, data]]]) 
tested with Python27 and Python33  by  vegaseat
'''

try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

# find yourself a picture on an internet web page you like
# (right click on the picture, look under properties and copy the address)
url = "http://www.google.com/intl/en/images/logo.gif"

filename = "logo.gif"

# retrieve the image from the url and save it to file
urlretrieve(url, filename)

print("image saved as %s"  % filename)

# try to show the saved image file ...
import webbrowser
webbrowser.open(filename)
snippsat 661 Master Poster

Some additional info.
Sometime it can convenient to not type in filename manually,but extract filename from url.
Like when downloading more than one image or iterate over a list of url`s.

strip() is not needed here for a single image.
But can be needed if iterating over many url`s to strip of new line(\n)

import webbrowser
try:
    # Python2
    from urllib import urlretrieve
except ImportError:
    # Python3
    from urllib.request import urlretrieve

url = "http://www.google.com/intl/en/images/logo.gif"

# Take out filname from url
filename = url.strip().split('/')[-1]
urlretrieve(url.strip(), filename)
print("image saved as {}".format(filename))

# try to show the saved image file ...
webbrowser.open(filename)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.