How do i automatically download a file from a website using python?


Python provides different modules like urllib, requests etc to download files from the web. I am going to use the request library of python to efficiently download files from the URLs.

Let’s start a look at step by step procedure to download files using URLs using request library−

1. Import module

import requests
url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

3. Save the content with name.

open('facebook.ico', 'wb').write(r.content)

save the file as facebook.ico.

Example

import requests


url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

open('facebook.ico', 'wb').write(r.content)

Result

How do i automatically download a file from a website using python?

We can see the file is downloaded(icon) in our current working directory.

But we may need to download different kind of files like image, text, video etc from the web. So let’s first get the type of data the url is linking to−

>>> r = requests.get(url, allow_redirects=True)
>>> print(r.headers.get('content-type'))
image/png

However, there is a smarter way, which involved just fetching the headers of a url before actually downloading it. This allows us to skip downloading files which weren’t meant to be downloaded.

>>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
False
>>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
True

To restrict the download by file size, we can get the filezie from the content-length header and then do as per our requirement.

contentLength = header.get('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb approx
return False

Get filename from an URL

To get the filename, we can parse the url. Below is a sample routine which fetches the last string after backslash(/).

url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
if url.find('/'):
print(url.rsplit('/', 1)[1]

Above will give the filename of the url. However, there are many cases where filename information is not present in the url for example – http://url.com/download. In such a case, we need to get the Content-Disposition header, which contains the filename information.

import requests
import re

def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0]


url = 'http://google.com/favicon.ico'
r = requests.get(url, allow_redirects=True)
filename = getFilename_fromCd(r.headers.get('content-disposition'))
open(filename, 'wb').write(r.content)

The above url-parsing code in conjunction with above program will give you filename from Content-Disposition header most of the time.

How do i automatically download a file from a website using python?

Updated on 30-Jul-2019 22:30:26

  • Related Questions & Answers
  • Downloading file using SAP .NET Connector
  • How are files extracted from a tar file using Python?
  • Rename multiple files using Python
  • Using SAP Web Service from WSDL file
  • Web Scraping using Python and Scrapy?
  • Python Implementing web scraping using lxml
  • How to copy files from one folder to another using Python?
  • How to copy files from one server to another using Python?
  • How to convert PDF files to Excel files using Python?
  • How to copy certain files from one folder to another using Python?
  • Implementing web scraping using lxml in Python?
  • Does HTML5 allow you to interact with local client files from within a web browser?
  • Generate temporary files and directories using Python
  • How to remove swap files using Python?
  • How to create powerpoint files using Python

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

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:

    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.

    import requests 

    from bs4 import BeautifulSoup 

    def get_video_links(): 

        r = requests.get(archive_url) 

        soup = BeautifulSoup(r.content,'html5lib'

        links = soup.findAll('a'

        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: 

            file_name = link.split('/')[-1

            print( "Downloading file:%s"%file_name) 

            r = requests.get(link, stream = True

            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__"

        video_links = get_video_links() 

        download_video_series(video_links) 

    Advantages of using Requests library to download web files are:

    • One can easily download the web directories by iterating recursively through the website!
    • This is a browser-independent method and much faster!
    • One can simply scrape a web page to get all the file URLs on a webpage and hence, download all files in a single command-

      Implementing Web Scraping in Python with BeautifulSoup

    This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


    How do you automate the download of a file from a website with Python?

    “how to automate downloading a file from a website using python” Code Answer's.
    import urllib. request..
    pdf_path = "".
    def download_file(download_url, filename):.
    response = urllib. request. urlopen(download_url).
    file = open(filename + ".pdf", 'wb').
    file. write(response. read()).
    file. close().

    How do you make a file downloadable in Python?

    Import module. import requests..
    Get the link or url. url = 'https://www.facebook.com/favicon.ico' r = requests.get(url, allow_redirects=True).
    Save the content with name. open('facebook.ico', 'wb').write(r.content) save the file as facebook. ... .
    Get filename from an URL. To get the filename, we can parse the url..

    How do I download multiple files from a website using Python?

    Download multiple files in parallel with Python To start, create a function ( download_parallel ) to handle the parallel download. The function ( download_parallel ) will take one argument, an iterable containing URLs and associated filenames (the inputs variable we created earlier).