Python to Check Website Connectivity with Source Code

This directory contains a simple tool to check connectivity to a number of websites.

  • The input file websites.txt should contain website URLs, one per line.
  • The output file website_status.csv contains a two-column report with the URL of each checked site and its status.
  • The script simply checks whether the webserver returns a 200 status code.

The output file will be overwritten each time you run the tool.

Prerequisites

This project uses the third-party library requests as well as csv module from the Python standard library.

How to run the Script

To run this script, type

python check_connectivity.py
Code language: CSS (css)

in the directory where you have checked out these files. (If you have an IDE that lets you run Python files, and prefer to use that instead, make sure you configure it to set the working directory to the one which contains the input file.)

Source Code:

import csv
import requests
status_dict = {"Website": "Status"}
def main():
    with open("websites.txt", "r") as fr:
        for line in fr:
            website = line.strip()
            status = requests.get(website).status_code
            status_dict[website] = "working" if status == 200 \
                else "not working"
    # print(status_dict)
    with open("website_status.csv", "w", newline="") as fw:
        csv_writers = csv.writer(fw)
        for key in status_dict.keys():
            csv_writers.writerow([key, status_dict[key]])
if __name__ == "__main__":
    main()

Input:

websites.txt

https://google.com/
https://www.youtube.com/
https://www.bing.com/
https://programsolve.com/
https://www.wikipedia.org/Code language: JavaScript (javascript)

Output:

website_status.csv

1WebsiteStatus
2https://www.google.com/ working
3https://www.youtube.com/ working
4https://www.bing.com/ working
5https://programsolve.com/ working
6https://www.wikipedia.org/ working

Leave a Comment