How to download from a URL?

Python – Download from a URL

To download from a URL, use the requests module. Call requests.get() function and pass the URL as argument. The function call requests.get() returns the response received from the URL and we can save it to a file.

We can download HTML pages, images, zip files, PDF files, etc., by following this tutorial.

Step by step process

  1. Import requests module.
  2. Make URL string available.
  3. Call requests.get() function and pass the URL as argument. Store the response.
  4. Save the response content to a file using Python built-in function open(): Open the file in wb, write binary mode, and write the response.content to the file.

Examples

1. Download HTML Page from URL

In the following program, we download the HTML webpage from the URL https://pythonexamples.org/, and and save it to a file with the name download.html.

Python Program

import requests

URL = "https://pythonexamples.org/"
response = requests.get(URL)

with open("download.html", "wb") as htmlFile:
    htmlFile.write(response.content)
    print('Download completed.')

You can replace replace the URL string with the URL of webpage that you would like to download, and also can change the file name download.html to whatever filename you would deem fit.

Output

Download completed.

In this program, we have saved the HTML content to a file in the same location as our Python file. Instead, you can specify a relative path, or a complete path, to save the file to a different location.

2. Download Image from URL

In the following program, we download the HTML webpage from the URL https://pythonexamples.org/, and and save it to a file with the name download.html.

Python Program

import requests

imageURL = "https://pythonexamples.org/wp-content/uploads/2019/02/python-examples-190.png"
response = requests.get(imageURL)

with open("image.png", "wb") as imageFile:
    imageFile.write(response.content)
    print('Image download completed.')

You can replace the URL string with the URL of an image that you would like to download, and also can change the file name image.png to whatever filename you would deem fit.

Output

Image download completed.

3. Download other File types

Similar to the previous examples, you can download any type of files like PDF, zip, etc.

All you need to do is replace the URL with the URL of the resource you would want to download.

Summary

In this tutorial of Python Examples, we learned how to download HTML page, image, PDF, zip, or any other file, using requests module.

Related Tutorials

Code copied to clipboard successfully 👍