Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to locally save an image using Urllib

Vinisha Maheshwari

In this shot, we will discuss how to save an image in Python using Urllib.

Sometimes, it is essential to download image(s), especially when we work on certain projects.

Although we can manually download images, save them to our local drives and use them in the required application, the process can be automated by writing simple Python scripts using the Urllib library.

The Urllib library

Urllib is a standard Python library for accessing websites, downloading and parsing data, POST requests, etc.


Let’s look at the code snippet below.

import urllib.request
import os

# Adding user_agent information
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]

# Image URL and Filename
filename = "pic.jpg"
image_url = ""

# Get resource
urllib.request.urlretrieve(image_url, filename)

Implementing Urllib in Python


  • In line 2, we imported the necessary library.

  • In lines 5 to 7, we added information about the user agent, so downloading the image becomes feasible.

  • In lines 10 and 11, we assigned the image url and the file directory.

  • In line 14, the urllib.request.urlretrieve() function is used to retrieve the image from the given url and store it to the required file directory.

  • In line 16, we printed the files and folders available in the current directory. Here, we can verify that the image has been downloaded and saved locally.

In this way, we can save an image locally by using a URL address using Urllib in Python.



View all Courses

Keep Exploring