Ensuring that websites are up and running smoothly is critical, but manually checking if front-end services are operational on multiple websites can be a tedious task. By automating this process with Python, we can streamline these checks and receive alerts when something goes wrong.
Let’s create an automated system that logs into multiple websites daily, verifies that their login functionality is working correctly, and sends an SMS alert using Twilio if any website fails. We’ll utilize Python libraries like selenium
for web automation, schedule
for running the checks at specified intervals, pyautogui
for automating GUI interactions, and Twilio for sending SMS notifications.
Step 1: Setting Up the Project Environment
Let’s start by setting up a virtual environment for our project to keep the dependencies isolated. This ensures that our project’s libraries don’t conflict with other Python projects on the system.
Create a project directory:
mkdir website_monitoring
cd website_monitoring
Create and activate a virtual environment:
python -m venv env
source env/bin/activate # For Mac/Linux
.\env\Scripts\activate # For Windows
Install the required libraries: We’ll need to install the following libraries:
selenium
: For automating the login process on websites.schedule
: For scheduling our script to run at specific intervals.pyautogui
: For any potential GUI interactions, such as handling pop-ups.twilio
: For sending SMS alerts in case of failures.
Install them using pip:
pip install selenium schedule pyautogui twilio
You will also need to download the appropriate ChromeDriver for your version of Chrome, which selenium
will use to interact with websites. Download it from: https://chromedriver.chromium.org/downloads
Place the chromedriver
executable in your project folder.
Step 2: Writing the Automation Script
Our goal is to log in to several websites, verify that the login was successful, and if any login fails, trigger an SMS alert using Twilio.
1. Setting Up Twilio SMS Notifications
First, create an account on Twilio and get your Twilio account SID, authentication token, and phone number. These will be needed to send SMS messages.
Create a Python file named monitor_websites.py
and add the following code:
from selenium import webdriver
from selenium.webdriver.common.by import By
import schedule
import pyautogui
import time
from twilio.rest import Client
# Twilio configuration
TWILIO_ACCOUNT_SID = 'your_account_sid'
TWILIO_AUTH_TOKEN = 'your_auth_token'
TWILIO_PHONE_NUMBER = 'your_twilio_phone_number'
ALERT_PHONE_NUMBER = 'recipient_phone_number'
# Initialize Twilio client
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
# Path to the ChromeDriver
chrome_driver_path = './chromedriver'
# List of websites to monitor
websites = [
{
'url': 'https://example.com/login',
'username_field': 'name=username',
'password_field': 'name=password',
'username': 'your_username',
'password': 'your_password',
'submit_button': '//button[@type="submit"]'
},
# Add more websites here
]
def send_sms_alert(message):
"""Send an SMS alert via Twilio."""
client.messages.create(
body=message,
from_=TWILIO_PHONE_NUMBER,
to=ALERT_PHONE_NUMBER
)
def check_website(website):
"""Check if the website's login page is working."""
driver = webdriver.Chrome(executable_path=chrome_driver_path)
try:
driver.get(website['url'])
time.sleep(2)
# Find the username and password fields and input the login credentials
username_field = driver.find_element(By.NAME, website['username_field'].split('=')[1])
password_field = driver.find_element(By.NAME, website['password_field'].split('=')[1])
username_field.send_keys(website['username'])
password_field.send_keys(website['password'])
# Submit the form
submit_button = driver.find_element(By.XPATH, website['submit_button'])
submit_button.click()
time.sleep(3) # Wait for the login to process
# Verify if login was successful (this may need customization depending on the website)
if "dashboard" not in driver.current_url: # Check if we are redirected to a dashboard
raise Exception("Login failed")
print(f"Login successful for {website['url']}")
except Exception as e:
error_message = f"Login failed for {website['url']}: {str(e)}"
print(error_message)
send_sms_alert(error_message)
finally:
driver.quit()
def monitor_websites():
"""Monitor all websites in the list."""
for website in websites:
check_website(website)
# Schedule the task to run every day at 9 AM
schedule.every().day.at("09:00").do(monitor_websites)
# Run the scheduler
while True:
schedule.run_pending()
time.sleep(1)
Step 3: How the Code Works
1. Twilio SMS Setup
The send_sms_alert
function is responsible for sending an SMS notification via Twilio. It takes a message as an argument and sends it to a specified phone number using the Twilio client. Make sure to replace the placeholder values (TWILIO_ACCOUNT_SID
, TWILIO_AUTH_TOKEN
, etc.) with the actual credentials from your Twilio account.
2. Website Monitoring Logic
The check_website
function handles logging into each website in the websites
list. It uses selenium
to:
- Navigate to the website’s login page.
- Enter the username and password.
- Submit the login form.
- Check whether the login was successful by verifying the URL or another condition (in this case, the URL redirection to a dashboard page).
If login fails (for example, the website doesn’t respond or login credentials are rejected), the script triggers an SMS alert with details about the failure.
3. Scheduling the Task
The script uses the schedule
library to ensure that the monitor_websites
function runs every day at 9 AM. The schedule.every().day.at("09:00").do(monitor_websites)
line schedules this task, while the infinite loop at the bottom ensures that the script continuously checks for pending scheduled tasks.
Step 4: Running the Script
To start monitoring your websites, simply run the script from your terminal:
python monitor_websites.py
This will trigger daily checks at 9 AM. If any website fails to log in as expected, an SMS alert will be sent to the designated phone number.
Step 5: Customizing the Script
- Additional Websites: You can easily add more websites by extending the
websites
list with new login pages and credentials. - Failure Detection: Depending on the websites you are monitoring, you might need to customize the login success/failure detection logic. For example, some websites may not redirect to a dashboard and instead show a success message or remain on the same page with different content.
- Error Handling: You can expand the error handling logic to capture more specific issues, such as network failures, CAPTCHA challenges, or session timeouts.
Thank you for reading this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!
You can find the same tutorial on Medium.com.