Robert Johns | 20 Feb, 2025
Fact checked by Jim Markus

Build a Python Site Connectivity Checker App with PyQt (Step-by-Step)

Want to check if a website is online or down? This project will teach you how to build a GUI-based Site Connectivity Checker using Python and PyQt5. We'll design a modern, interactive interface with a clean look.

What You Will Learn:

- Building a PyQt5 GUI Application
- Using urllib.request to check website availability
- Applying Object-Oriented Programming (OOP) for structuring the app
- Styling the PyQt5 app for a modern look
- Handling errors and improving user experience

Step 1: Setting Up the Project

Before we start coding, let’s set up our Python project:

1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, site_connectivity_checker.py.

Great, now, let's dive head first into our Python editor to get this build started to produce something like I've shown below:

A Python-based Site Connectivity Checker with a PyQt5 graphical interface that allows users to verify website availability, utilizing network requests and error handling for an interactive desktop application

Step 2: Understanding the Project

Our Site Connectivity Checker will:

  • Allow users to input a website URL.
  • Use urllib.request to check the status code of the site.
  • Display whether the site is available (200 OK) or down.
  • Include a responsive PyQt5 GUI with modern styling.

And don't worry if you're not sure how to create a GUI with PyQt, I've got you covered. Plus, I've also created a detailed guide on how to use PyQt if you want some extra help.

Step 3: Importing Required Modules

We need the following Python modules:

import sys
import urllib.request
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
from PyQt5.QtGui import QFont, QPalette, QColor

Why These Modules?

  • sys → Required for running a PyQt5 application.

  • urllib.request → Checks if a website is accessible.

  • PyQt5.QtWidgets → Builds the user interface.

  • PyQt5.QtGui → Customizes fonts and colors for a better UI experience.

Step 4: Sketching Out the Class and Methods

We'll structure our PyQt5 GUI application using a class-based approach via OOP in Python.

class SiteCheckerApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        """Initializes the UI layout and widgets."""
        pass
    
    def check_site(self):
        """Checks if the entered website is online or down."""
        pass

Why Use OOP for This App?

  • Encapsulation:

    • The application logic and UI components are grouped into a single class, making the code more modular and reusable.

  • Class Constructor (__init__ Method):

    • Calls super().__init__() to inherit properties from QWidget.

    • Calls self.init_ui() to set up the graphical user interface.

  • init_ui() Method:

    • Handles widget layout and visual styling.

    • Adds input fields, labels, and buttons to the window.

  • check_site() Method:

    • Validates user input and checks the connectivity of the entered URL.

    • Uses urllib.request.urlopen() to determine the website's availability.

This class-based approach ensures the code is organized, scalable, and maintainable, making it easy to extend functionality in future updates.

Step 5: Implementing the UI with PyQt5

def init_ui(self):
    """Initializes the UI layout and widgets with styling."""
    self.setWindowTitle("Site Connectivity Checker")
    self.setGeometry(100, 100, 400, 200)
    
    # Apply custom font and palette
    app_font = QFont("Arial", 12)
    self.setFont(app_font)
    
    layout = QVBoxLayout()
    
    self.label = QLabel("Enter website URL (https://...):")
    self.label.setStyleSheet("color: #003366; font-size: 14px; font-weight: bold;")
    layout.addWidget(self.label)
    
    self.url_input = QLineEdit(self)
    self.url_input.setPlaceholderText("Enter website URL")
    self.url_input.setStyleSheet("""
        QLineEdit {
            border: 2px solid #007BFF;
            border-radius: 5px;
            padding: 8px;
            font-size: 14px;
        }
    """)
    layout.addWidget(self.url_input)
    
    self.check_button = QPushButton("Check Connectivity", self)
    self.check_button.setStyleSheet("""
        QPushButton {
            background-color: #007BFF;
            color: white;
            border-radius: 5px;
            padding: 10px;
            font-size: 14px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #0056b3;
        }
    """)
    self.check_button.clicked.connect(self.check_site)
    layout.addWidget(self.check_button)
    
    self.result_label = QLabel("")
    self.result_label.setStyleSheet("color: #003366; font-size: 14px;")
    layout.addWidget(self.result_label)
    
    self.setLayout(layout)
    
    # Apply overall window styling
    self.setStyleSheet("""
        QWidget {
            background-color: #f7f9fc;
        }
    """)

How It Works:

  • Sets up the main window

    • Defines a title for the application (setWindowTitle)

    • Sets a fixed size (setGeometry) to ensure consistency across different screens.

  • Creates and styles a label for user instructions

    • The label QLabel instructs users to input a website URL.

    • Styles it with bold text and a custom color.

  • Adds an input field (QLineEdit) for URL entry

    • Provides a placeholder text to guide users.

    • Styles the field with a border, padding, and rounded corners for a clean look.

  • Implements a 'Check Connectivity' button (QPushButton)

    • Clicking the button triggers the check_site function.

    • Uses hover effects to make interactions smoother.

  • Displays results dynamically (QLabel)

    • Initially blank, updated dynamically based on website status.

  • Applies an overall application theme (setStyleSheet)

    • Sets a light blue background for a professional appearance.

    • Ensures a cohesive UI with consistent colors and fonts.

This design makes the app user-friendly, visually appealing, and easy to use while ensuring clear instructions and feedback for users.

Step 6: Implementing Site Checking Logic

def check_site(self):
    """Checks if the entered website is online or down."""
    website = self.url_input.text().strip()
    
    if not website.startswith("http"):
        QMessageBox.warning(self, "Invalid URL", "Please enter a valid URL starting with http or https.")
        return
    
    try:
        status_code = urllib.request.urlopen(website).getcode()
        if status_code == 200:
            self.result_label.setText("Website is Available")
        else:
            self.result_label.setText("Website is Not Available")
    except Exception as e:
        self.result_label.setText("Could not reach website")

How It Works:

  • Extracts user input (QLineEdit):

    • Retrieves the entered URL and removes unnecessary spaces with .strip().

    • Ensures the input starts with http or https to prevent errors.

  • Validates user input:

    • If the user enters an invalid URL (e.g., missing http://), it displays a warning using QMessageBox.warning().

  • Attempts to open the website (urllib.request.urlopen()):

    • Sends an HTTP request to the specified URL.

    • Retrieves the HTTP status code for evaluation.

  • Checks the status code:

    • If 200, the website is online and accessible.

    • If the response is anything other than 200, it indicates that the site is not available.

  • Handles exceptions:

    • If the request fails (e.g., no internet connection, incorrect URL, site downtime), an error message is displayed via the try-except block.

    • The result label updates dynamically to notify the user.

This function ensures a robust and user-friendly approach to checking website connectivity while handling errors gracefully.

Step 7: Running the PyQt5 App

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SiteCheckerApp()
    window.show()
    sys.exit(app.exec_())

How It Works:

  • Initializes the PyQt5 application (QApplication):

    • The QApplication object manages the event loop and GUI execution.

    • sys.argv ensures proper command-line argument handling.

  • Creates an instance of the SiteCheckerApp class:

    • This initializes the GUI and prepares the widgets.

  • Displays the main application window:

    • window.show() makes the PyQt5 application visible to the user.

  • Starts the event loop (sys.exit(app.exec_())):

    • The event loop waits for user actions (button clicks, text input, etc.).

    • sys.exit() ensures a clean exit when the application is closed.

By structuring the program this way, we ensure a smooth, interactive, and responsive user experience while maintaining best practices for GUI applications.

Final Code: Site Connectivity Checker

import sys
import urllib.request
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
from PyQt5.QtGui import QFont

class SiteCheckerApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        """Initializes the UI layout and widgets with styling."""
        self.setWindowTitle("Site Connectivity Checker")
        self.setGeometry(100, 100, 400, 200)
        
        # Apply custom font and palette
        app_font = QFont("Arial", 12)
        self.setFont(app_font)
        
        layout = QVBoxLayout()
        
        self.label = QLabel("Enter website URL (https://...):")
        self.label.setStyleSheet("color: #003366; font-size: 14px; font-weight: bold;")
        layout.addWidget(self.label)
        
        self.url_input = QLineEdit(self)
        self.url_input.setPlaceholderText("Enter website URL")
        self.url_input.setStyleSheet("""
            QLineEdit {
                border: 2px solid #007BFF;
                border-radius: 5px;
                padding: 8px;
                font-size: 14px;
            }
        """)
        layout.addWidget(self.url_input)
        
        self.check_button = QPushButton("Check Connectivity", self)
        self.check_button.setStyleSheet("""
            QPushButton {
                background-color: #007BFF;
                color: white;
                border-radius: 5px;
                padding: 10px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
        self.check_button.clicked.connect(self.check_site)
        layout.addWidget(self.check_button)
        
        self.result_label = QLabel("")
        self.result_label.setStyleSheet("color: #003366; font-size: 14px;")
        layout.addWidget(self.result_label)
        
        self.setLayout(layout)
        
        # Apply overall window styling
        self.setStyleSheet("""
            QWidget {
                background-color: #f7f9fc;
            }
        """)
    
    def check_site(self):
        website = self.url_input.text().strip()
        if not website.startswith("http"):
            QMessageBox.warning(self, "Invalid URL", "Please enter a valid URL starting with http or https.")
            return
        try:
            status_code = urllib.request.urlopen(website).getcode()
            self.result_label.setText("Website is Available" if status_code == 200 else "Website is Not Available")
        except Exception:
            self.result_label.setText("Could not reach website")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SiteCheckerApp()
    window.show()
    sys.exit(app.exec_())

Wrapping Up

Congratulations! You’ve built a fully functional site connectivity checker in Python using PyQt5.

What You Learned:

- Building a PyQt5 GUI application from scratch
- Using urllib.request to check website connectivity
- Structuring Python code using OOP principles
- Enhancing UI with custom styling and layouts
- Implementing error handling for better user experience

Next Steps:

- Add a feature to check multiple websites at once.
- Store website test history for quick reference.
- Integrate an API for real-time website monitoring.
- Enhance UI with advanced animations and transitions.

The best way to learn Python is by building real projects—so keep experimenting!

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments