Downloading files from web using Python
Last Updated :
28 Jun, 2022
Requests is a versatile HTTP library in python with various applications. One of its applications is to download a file from web using the file URL.
Installation: First of all, you would need to download the requests library. You can directly install it using pip by typing following command:
pip install requests
Or download it directly from
here and install manually.
Downloading files
Python3
# imported the requests library
import requests
image_url = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"
# URL of the image to be downloaded is defined as image_url
r = requests.get(image_url) # create HTTP response object
# send a HTTP request to the server and save
# the HTTP response in a response object called r
with open("python_logo.png",'wb') as f:
# Saving received content as a png file in
# binary format
# write the contents of the response (r.content)
# to a new file in binary mode.
f.write(r.content)
This small piece of code written above will download the following image from the web. Now check your local directory(the folder where this script resides), and you will find this image:
All we need is the URL of the image source. (You can get the URL of image source by right-clicking on the image and selecting the View Image option.)
Download large files
The HTTP response content (
r.content) is nothing but a string which is storing the file data. So, it won’t be possible to save all the data in a single string in case of large files. To overcome this problem, we do some changes to our program:
Since all file data can't be stored by a single string, we use r.iter_content method to load data in chunks, specifying the chunk size.
r = requests.get(URL, stream = True)
Setting
stream parameter to
True will cause the download of response headers only and the connection remains open. This avoids reading the content all at once into memory for large responses. A fixed chunk will be loaded each time while
r.iter_content is iterated.
Here is an example:
Python3
import requests
file_url = "http://codex.cs.yale.edu/avi/db-book/db4/slide-dir/ch1-2.pdf"
r = requests.get(file_url, stream = True)
with open("python.pdf","wb") as pdf:
for chunk in r.iter_content(chunk_size=1024):
# writing one chunk at a time to pdf file
if chunk:
pdf.write(chunk)
Downloading Videos
In this example, we are interested in downloading all the video lectures available on this
web-page. All the archives of this lecture are available
here. So, we first scrape the webpage to extract all video links and then download the videos one by one.
Python3
import requests
from bs4 import BeautifulSoup
'''
URL of the archive web-page which provides link to
all video lectures. It would have been tiring to
download each video manually.
In this example, we first crawl the webpage to extract
all the links and then download videos.
'''
# specify the URL of the archive here
archive_url = "http://www-personal.umich.edu/~csev/books/py4inf/media/"
def get_video_links():
# create response object
r = requests.get(archive_url)
# create beautiful-soup object
soup = BeautifulSoup(r.content,'html5lib')
# find all links on web-page
links = soup.findAll('a')
# filter the link sending with .mp4
video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp4')]
return video_links
def download_video_series(video_links):
for link in video_links:
'''iterate through all links in video_links
and download them one by one'''
# obtain filename by splitting url and getting
# last string
file_name = link.split('/')[-1]
print( "Downloading file:%s"%file_name)
# create response object
r = requests.get(link, stream = True)
# download started
with open(file_name, 'wb') as f:
for chunk in r.iter_content(chunk_size = 1024*1024):
if chunk:
f.write(chunk)
print( "%s downloaded!\n"%file_name )
print ("All videos downloaded!")
return
if __name__ == "__main__":
# getting all video links
video_links = get_video_links()
# download all videos
download_video_series(video_links)
Advantages of using Requests library to download web files are:
This blog is contributed by Nikhil Kumar.
Similar Reads
How to Download Files from Urls With Python
Here, we have a task to download files from URLs with Python. In this article, we will see how to download files from URLs using some generally used methods in Python. Download Files from URLs with PythonBelow are the methods to Download files from URLs with Python: Using 'requests' ModuleUsing 'url
2 min read
How to download Google Images using Python
Python is a multi-purpose language and widely used for scripting. We can write Python scripts to automate day-to-day things. Letâs say we want to download google images with multiple search queries. Instead of doing it manually we can automate the process. How to install needed Module :Â pip install
2 min read
How To Upload And Download Files From AWS S3 Using Python?
Pre-requisite: AWS and S3Amazon Web Services (AWS) offers on-demand cloud services which means it only charges on the services we use (pay-as-you-go pricing). AWS S3 is a cloud storage service from AWS. S3 stands for 'Simple Storage Service. It is scalable, cost-effective, simple, and secure. We gen
3 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uplo
7 min read
How to download Files with Scrapy ?
Scrapy is a fast high-level web crawling and web scraping framework used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing. In this tutorial, we will be exploring how to download files usi
8 min read
Upload and Download files from Google Drive storage using Python
In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let's go ahead and write a Pytho
6 min read
How to Check Loading Time of Website using Python
In this article, we will discuss how we can check the website's loading time. Do you want to calculate how much time it will take to load your website? Then, what you must need to exactly do is subtract the time obtained passed since the epoch from the time obtained after reading the whole website.
3 min read
Download Instagram Posts Using Python Selenium module
In this article, we will learn how we can download Instagram posts of a profile using Python Selenium module. Requirements:Google Chrome or FirefoxChrome driver(For Google Chrome) or Gecko driver(For Mozilla Firefox)Selenium package: It is a powerful tool for controlling a web browser through the pr
7 min read
Creating and Viewing HTML files with Python
Python is one of the most versatile programming languages. It emphasizes code readability with extensive use of white space. It comes with the support of a vast collection of libraries which serve for various purposes, making our programming experience smoother and enjoyable. Python programs are us
3 min read
Extract title from a webpage using Python
Prerequisite Implementing Web Scraping in Python with BeautifulSoup, Python Urllib Module, Tools for Web Scraping In this article, we are going to write python scripts to extract the title form the webpage from the given webpage URL. Method 1: bs4 Beautiful Soup(bs4) is a Python library for pulling
3 min read