Fun with python requests module

I was reading this part of the pym book and thought that I should change this code a little bit so that it can do some better thing like instead of storing the content in a text file it stores it in a HTML file and it also checks if there is any same named file exists in the directory or not. Here is the code –

import os.path
import requests

def download(url):
    Download the given url and saves it to the current directory
    :arg url: URL of the file to be downloaded.
    req = requests.get(url)
    if req.status_code == 404:
        print('No such file found at %s' % url)
    fileName = url.split('/')[-1].split('.')[0] + '.html'
    if os.path.isfile(fileName):
        print('Same file name already exist')
        with open(fileName, 'wb') as fobj:
        print('Download over')

if __name__ == "__main__":
    url = input("Enter a URL: ")

Above we are getting the content of the content of the url by requests.get(url) method. Then checking if that url is valid or not. If valid then parsing the url by split() method like first we are splitting it by “/” and taking the last value of the list and then splitting it again with “.” and taking the first value of the list. Then checking if there is no same name file exist and if there is no same name file then we are creating a file then writing the content in the file.
Thank you 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s