This code example demonstrates a robust approach to testing a website using Python and Selenium, along with other libraries such as difflib, requests, os, and subprocess. The code navigates to a spec

07 April 2023 Alejandro Acosta

This code example demonstrates a robust approach to testing a website using Python and Selenium, along with other libraries such as difflib, requests, os, and subprocess. The code navigates to a specified URL, takes a screenshot of the page, and compares the text of the page with an expected text using the difflib library.

It also checks for any broken links on the page using the requests library and takes a screenshot of any broken links if they are found.

Additionally, the code checks for any visual changes on the page using the ImageMagick command-line tool and the Python os and subprocess libraries.

from selenium import webdriver

from https://lnkd.in/eyphV6mv import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

import difflib

import time

import requests

import os

url = "https://www.example.com"

expected_text = "Welcome to Example.com"

driver_path = "/path/to/chromedriver"

screenshot_dir = "/path/to/screenshots"

def take_screenshot(driver, file_name):

if not os.path.exists(screenshot_dir):

os.makedirs(screenshot_dir)

driver.save_screenshot(os.path.join(screenshot_dir, file_name))

def compare_text(driver):

page_text = driver.find_element_by_tag_name("body").text

ratio = difflib.SequenceMatcher(None, expected_text, page_text).ratio()

return ratio >= 0.9

options = webdriver.ChromeOptions()

options.add_argument("--headless")

driver = webdriver.Chrome(driver_path, options=options)

driver.set_window_size(1920, 1080)

driver.get(url)

wait = WebDriverWait(driver, 10)

wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))

screenshot_name = f"{url.replace('https://', '')}_{int(time.time())}.png"

take_screenshot(driver, screenshot_name)

assert compare_text(driver)

broken_links = []

links = driver.find_elements_by_tag_name("a")

for link in links:

url = link.get_attribute("href")

if url.startswith("mailto:"):

continue

try:

response = requests.head(url, allow_redirects=True, timeout=5)

if response.status_code >= 400:

broken_links.append(url)

except:

broken_links.append(url)

if broken_links:

screenshot_name = f"{url.replace('https://', '')}_broken_links_{int(time.time())}.png"

take_screenshot(driver, screenshot_name)

raise Exception(f"Found broken links: {broken_links}")

expected_image = "/path/to/expected_image.png"

screenshot_image = os.path.join(screenshot_dir, screenshot_name)

if not os.path.exists(expected_image):

os.rename(screenshot_image, expected_image)

else:

os.system(f"compare -metric AE -fuzz 5% {expected_image} {screenshot_image} /dev/null 2>&1")

difference = int(os.popen(f"identify -format %[distortion] {screenshot_image}").read().strip())

if difference > 1000:

raise Exception(f"Found visual changes: {screenshot_image}")

driver.quit()