Create Website Blocker using Python

In this Python Project, we will build a GUI-based Website Blocker for Windows and Linux which will also have an option to unblock the blocked websites.

It is an intermediate-level project, and you should have knowledge about gui applications and computer networking before you begin. You will also need to have knowledge about Python File I/O. If you do not know, no worries, we will explain all of them. Let’s build this interesting python project!

About Website Blocker

Website blockers are software programs that are used to block any websites on the internet and prevent us from accessing them. They are most widely used as browser extensions that “Blacklist” websites for you so that you cannot see the results from those websites. But here, we are going to create a program that blocks websites and you cannot access those blocked websites.

About Website Blocker Project:

The objective of this project is to create a GUI-based website blocker for windows as well as linux, which will also have an option to unblock those websites. For this project, you will need basic understanding of Tkinter library widgets and the messagebox components of the Tkinter library.

Project Prerequisites:

To create this python project, you will need basic understanding of python file I/O, python data structures, and a basic understanding of Tkinter library. We are only going to need the Tkinter library to create the GUI, and it comes pre-installed with Python.

Knowledge Prerequisites:

To work on python website blocker you will also need some more knowledge about networking, web app, etc. not related to Python, to create this project and code it.

Computer Networking:

  • localhost – It is a set of hostnames that refer to your local computer to access the network services being used by your computer. These hostnames usually start with ‘127’.
  • hostname – It is an IP address (not specifically on your computer) that is used to identify your computer during electronic communications.
  • localhost 127.0.0.1 – It is a localhost address called the “Internet Loopback Protocol”. This address is used to establish an IP connection to the same machine or computer being used by the end-user.
  • hosts file – It is an operating system file that is used to map a connection between an IP address (localhost in our case) and a domain name, before actually going to the domain name servers. It is a .txt file that contains a mapping of the IP addresses and domain names. It no longer has an extension but can still only be edited as a .txt file. It has different locations on different OSs, i.e., it has a different location on Windows and Linux, but the same location on MAC and Linux.

Web Applications:

  • Every domain name has its own IP address and when you type that domain name on your browser, it takes you to its IP address, and vice versa.
  • For example, If you type 142.250.77.110 on your URL bar, it will take you to google.com, because that is Google.com’s IP address (Try it!).

How does it work?

Well, now that you have enough knowledge required for the python website blocker project, let us tell you how it works.

The hosts file, as you know, maps addresses to domains; and when you type 127.0.0.1 on the URL bar on your browser, it always refuses to connect (as on local machine usually we don’t run a web server). So, to block websites, we will map your desired websites to the localhost address 127.0.0.1 and add that to the hosts file. Similarly, to unblock the website, we will remove that line from the hosts file.

Download Website Blocker Python Code

Please download the source code of python website blocker: Website Blocker Python Code

Project File Structure:

  1. blocked_websites.txt – A text file we will create that contains a list of all the blocked websites, something we will use while unblocking blocked websites. [This file must never be edited manually, or you might not be able to unblock a certain website]
  2. hosts (OS file) – An operating system file that maps IP addresses to domain names, before letting the computer go to the domain name servers.
  3. main.py – The source code Python file.

Steps to Develop Python Website Blocker

Here are all the steps that you will have to do to create this project.

  1. Importing all the necessary libraries.
  2. Setting the hosts file location and localhost address for the project.
  3. Creating a master GUI window, and placing all its components.
  4. Creating a block function for the Toplevel widget to block websites.
  5. Creating a nested block_websites in the block function, which will do the processing and eventually block the desired website(s).
  6. Creating an unblock function for the Toplevel widget to unblock websites.
  7. Creating a nested unblock_websites in the unblock function, which will process the desired website and unblock it.

Let’s take a closer and deeper look at all the steps:

1. Importing all the necessary libraries:

# Importing all the modules
from tkinter import *
from tkinter.messagebox import *

2. Setting the hosts file location and localhost address for the project:

# Setting the file location and the localhost IP address for the GUI
host_files = {
    'Windows': r"C:\Windows\System32\drivers\etc\hosts",
    'Linux': '/etc/host'     # Can also be used for MAC
}
localhost = '127.0.0.1'

Explanation:

  • As mentioned earlier, the location for the hosts file differs with the OS. The locations for Windows and Linux are mentioned here. For MAC users, you can use the same location as in Linux.
  • The r””, also known as R-string, has only one difference from the normal strings. That difference being, the R-string treats the “\” as a literal character, as opposed to being treated as an escape character by normal string.

3. Creating a master GUI window, and placing all its components:

# Creating a GUI master window
root = Tk()
root.title("ProjectGurukul Website Blocker")
root.geometry('400x300')
root.wm_resizable(False, False)

# Creating and setting the locations of all the components of the GUI
Label(root, text='ProjectGurukul Website Blocker', font=("Comic Sans MS", 16)).place(x=45, y=0)
Label(root, text='What do you want to do?', font=("Helvetica", 14)).place(x=90, y=40)

Button(root, text='Block a Website', font=('Times', 16), bg='SpringGreen4', command=lambda: block(root)).place(x=110, y=100)

Button(root, text='Unblock a Website', font=('Times', 16), bg='SpringGreen4', command=lambda: unblock(root)).place(x=100, y=150)

root.update()
root.mainloop()

Explanation:

To create a master GUI window, the essentials are:

title() method – This method adds a title to the project window.

geometry() method – This method gives dimensions to the window in pixels.

resizable() method – It takes the positional arguments in the form (height, width) and the defaults are (True, True) but you can also change to False or 0 to set a fixed size to the window.

Label widget – This widget is used to display text on the python website blocker window of any font or any background.

place() method – This is a Tkinter geometry manager method that allows the user to set the starting position of a widget according to the coordinates on a cartesian plane, where the north-west corner is the default. It takes the following options:

  • anchor – to change the position of (0,0) coordinate to any other corner/side of the window.
  • x, y – horizontal and vertical offsets on the cartesian plane.
  • height, width – height and width of the window.

Button widget – Used to add a button that performs a command when pressed, to the window. It takes the following parameters:

  • master – The root window.
  • options: (These are the ones discussed above)
    • text – text to be displayed on the Button
    • font – font family to be used to display the text. It goes in the form, (‘family’, size, ‘bold'(optional), ‘italic'(optional))
    • bg/background – background to be set to the button.
    • command – function to be executed when the button is pressed. It usually takes a function without arguments, but you need to use the lambda keyword if you want to assign a function with arguments.

4. Creating a block function for the top level widget to block websites:

def block(win):
    blck_wn = Toplevel(win, background='LightBlue')
    blck_wn.title("Block a website")
    blck_wn.geometry('300x200')
    blck_wn.resizable(False, False)

    Label(blck_wn, text='Block websites', background='LightBlue', font=("Georgia", 16)).place(x=80, y=0)
    Label(blck_wn, text='(Enter the websites separated *only* by \' , \')', background='LightBlue', font=("Times", 13)).place(x=0, y=35)
    Label(blck_wn, text='Enter the URLs (www.<sitename>.com):', background='LightBlue', font=('Times', 13)).place(x=0, y=70)

    sites = Text(blck_wn, width=35, height=3)
    sites.place(x=0, y=100)

    submit_btn = Button(blck_wn, text='Submit', bg='MidnightBlue', command=lambda: block_websites(sites.get('1.0',END)))
    submit_btn.place(x=100, y=160)

Explanation:

Text widget – It is a widget, used when the program expects a multiline input from the user. It takes the following arguments in website blocker project:

  • master – Associated window
  • width – Width of the widget.
  • height – Height of the widget, i.e., the maximum number of lines that can be displayed on the widget.

5. Creating a nested block_websites in the block function, which will do the processing and eventually block the desired website(s):

def block_websites(websites):
            # We are now going to get a list of all the blocked websites from the blocked_websites.txt file from its 3rd line
    with open('blocked_websites.txt', 'r+') as blocked_websites:
        blck_sites = blocked_websites.readlines()

    host_file = host_files['Windows']
    sites_to_block = list(websites.split(' , '))

    # First we will make a copy of the websites you want blocked to a text file called 'blocked_websites.txt'
    with open('blocked_websites.txt', 'r+') as blocked_websites_txt:
        blocked_websites_txt.seek(0, 2)
        for site in sites_to_block:
            blocked_websites_txt.write(site)

    with open(host_file, 'r+') as hostfile:
        content_in_file = hostfile.read()

        for site in sites_to_block:
            if site not in content_in_file:
                hostfile.write(localhost + '\t' + site + '\n')
                showinfo('Websites blocked!', message='We have blocked the websites you wanted blocked!')
            else:
                showinfo('Website Already blocked!', 'A website you entered is already blocked')

Explanation:

  • with open(filename.extension, mode) as nickname – This statement is used to open a file anywhere on the computer, and perform some actions on it. The actions that can be performed depend on the flag that was used.
  • “r+” mode – A mode that can be used to read and write the contents of a file.
  • seek() – This method is used to change the position of the cursor on the file. It takes 2 arguments:
    • offset – number of positions to move forward.
    • from_what – defines the point of reference. It has 3 options:
      • 0 – sets the point of reference to the beginning of the file.
      • 1 – sets the point of reference to the current position.
      • 2 – sets the point of reference to the end of the file.
  • showinfo – It is a Tkinter messagebox that displays some information on a python website blocker window, with an OK button to terminate that window.
  • In this function, we will get the text from our Text widget in the block function and convert them to a list of websites that we need to block. Then we will open and add these websites to the hosts file by mapping them to 127.0.0.1 address, and also put a copy of the blocked websites on the blocked_websites.txt file. And so, these websites will refuse to connect because they have been mapped to the wrong address.
  • .read() – This method returns the specified amount of data, in bytes to be fetched from the file. It takes one argument:
    • size – The number of bytes to return. Its default value is -1, i.e., returns the whole file.
  • write() – This method adds the text provided to it to the file.

6. Creating an unblock function for the top level widget to unblock websites:

def unblock(win):
    unblck_wn = Toplevel(win, background='Aquamarine')
    unblck_wn.title("Block a website")
    unblck_wn.geometry('285x200')
    unblck_wn.resizable(False, False)

    Label(unblck_wn, text='Unblock websites', background='Aquamarine', font=("Georgia", 16)).place(x=80, y=0)
    Label(unblck_wn, text='Select the URLs that you want to unblock:', background='Aquamarine', font=('Times', 13)).place(x=0, y=70)

    # Creating a dropdown menu from the textfile to get the sites that are blocked
    blck_sites_strvar = StringVar(unblck_wn)
    blck_sites_strvar.set(blck_sites[0])

    dropdown = OptionMenu(unblck_wn, blck_sites_strvar, *blck_sites)
    dropdown.config(width=20)
    dropdown.place(x=60, y=100)

    submit_btn = Button(unblck_wn, text='Submit', bg='MidnightBlue', command=lambda: unblock_websites(blck_sites_strvar.get()))
    submit_btn.place(x=100, y=160)

Explanation:

  • StringVar – This class, an alternative to the string objects in GUI, is used to manage the text in Label or Entry widgets. It takes 2 optional arguments:
    • master – The root window.
    • value – The initial value assigned to the StringVar object (To access this parameter, you will need to use the .set() method of this class)
  • OptionMenu – This widget is a dropdown menu associated with GUIs in Python. You have multiple values to choose from, just by clicking on the value. It takes 3 optional arguments:
    • master – The root window.
    • variable – The initial value. The default is ‘’.
    • *values – The list of values to choose from.

7. Creating a nested unblock_websites in the unblock function, which will process the desired website and unblock it:

def unblock_websites(websites_to_unblock):
     host_file = host_files['Windows']

     with open(host_file, 'r+') as hostfile:
         content_in_file = hostfile.readlines()
         hostfile.seek(0)

         for line in content_in_file:
             if not any(site in line for site in websites_to_unblock):
                 hostfile.write(line)

             hostfile.truncate()

     with open('blocked_websites.txt', 'r+') as blocked_websites_txt:
         file_content = blocked_websites_txt.readlines()
         blocked_websites_txt.seek(0)

         for line in file_content:
             if not any(site in line for site in websites_to_unblock):
                 blocked_websites_txt.write(line)

             blocked_websites_txt.truncate()


     Label(unblck_wn, text='Website Blocked!', font=("Times", 13), bg='Aquamarine').place()

Explanation:

  • readlines() – This method returns all the lines in a file, each element containing a line.
  • truncate() – This method reduces the file size to the given number of bytes. You can provide the desired number of bytes as arguments; if no argument is provided, then the file size will not be reduced.

Note:

When you run this file on your own machine, you are going to encounter a error called:

“PermissionError: [Errno 13] Permission denied:’C:\\Windows\\System32\\drivers\\etc\\hosts'”

To resolve this error, you need to provide required privileges to hosts file, naviaget to:
C:\\Windows\\System32\\drivers\\etc\\

Now right click on hosts file >> Properties >> Security >> Edit >> Provide Full control to user you are using

Python Website Blocker Output

python website blocker output

Summary

We have successfully created python website blocker for windows as well as linux where you can also unblock websites. This python project is going to be really applicable, since there are many irritating websites you might want to block. You can also use this to block Netflix, so you can focus during your classes, or for dopamine detoxification as well. This project is really practical and you will have a lot of fun with it!

Leave a Reply

Your email address will not be published. Required fields are marked *