Validating Links and Images Using Selenium
Validating links and images in web applications is essential for ensuring a smooth user experience. Broken links or missing images can negatively impact a website’s functionality and user trust. Selenium, combined with other libraries like requests, is a powerful tool to automate this validation process. Here's how to do it effectively.
Validating Links
To check if all hyperlinks on a page are working correctly:
Steps:
Use Selenium to extract all anchor (<a>) tags.
Get the href attribute for each link.
Use the requests library to send an HTTP request and check the response status code.
Python Example:
from selenium import webdriver
import requests
driver = webdriver.Chrome()
driver.get("https://example.com")
links = driver.find_elements("tag name", "a")
for link in links:
url = link.get_attribute("href")
if url:
try:
response = requests.head(url, allow_redirects=True, timeout=5)
if response.status_code >= 400:
print(f"Broken link: {url} (Status: {response.status_code})")
else:
print(f"Valid link: {url}")
except requests.exceptions.RequestException as e:
print(f"Error checking link: {url} - {e}")
driver.quit()
Validating Images
To check if image URLs are loading correctly:
Steps:
Find all image (<img>) tags using Selenium.
Extract the src attribute for each image.
Send an HTTP GET request to verify the image is accessible.
Python Example:
driver = webdriver.Chrome()
driver.get("https://example.com")
images = driver.find_elements("tag name", "img")
for img in images:
src = img.get_attribute("src")
if src:
try:
response = requests.get(src, stream=True, timeout=5)
if response.status_code >= 400:
print(f"Broken image: {src} (Status: {response.status_code})")
else:
print(f"Valid image: {src}")
except requests.exceptions.RequestException as e:
print(f"Error loading image: {src} - {e}")
driver.quit()
Tips for Reliable Validation
Avoid checking javascript:void(0) or empty href/src attributes.
Use timeouts and exception handling to prevent script failures on slow or unreachable resources.
Filter out duplicate URLs to reduce redundant checks
Conclusion
By automating the validation of links and images with Selenium and requests, you can quickly detect broken resources and maintain a healthy, user-friendly website. This approach helps testers catch issues early and ensures a smoother experience for end users.
Learn Selenium Python Training in Hyderabad
Read More:
Using Unittest Framework for Selenium Python
Cross-Browser Testing with Selenium in Python
Headless Browser Testing Using Selenium and Python
Handling Dynamic Elements in Selenium
Automating Scrolling and Navigation
Visit our IHub Talent Training Institute
Comments
Post a Comment