0
0
Selenium Pythontesting~5 mins

Checking element state (displayed, enabled, selected) in Selenium Python

Choose your learning style9 modes available
Introduction

We check if elements are visible, clickable, or selected to make sure our tests interact with the right parts of a webpage.

Before clicking a button, check if it is enabled to avoid errors.
Verify if a checkbox is selected before submitting a form.
Confirm that a popup or message is displayed before reading its content.
Ensure a link is visible before trying to click it.
Check if a radio button is selected to validate user choices.
Syntax
Selenium Python
element.is_displayed()
element.is_enabled()
element.is_selected()

is_displayed() returns True if the element is visible on the page.

is_enabled() returns True if the element can be interacted with (not disabled).

is_selected() returns True if the element is selected (mainly for checkboxes, radio buttons, and options).

Examples
Check if the submit button is enabled before clicking.
Selenium Python
button = driver.find_element(By.ID, "submit")
print(button.is_enabled())
Check if the subscribe checkbox is selected.
Selenium Python
checkbox = driver.find_element(By.NAME, "subscribe")
print(checkbox.is_selected())
Check if a popup message is visible on the page.
Selenium Python
popup = driver.find_element(By.CLASS_NAME, "popup-message")
print(popup.is_displayed())
Sample Program

This script opens a webpage with a checkbox, checks if it is visible, enabled, and selected before and after clicking it.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()
driver.get("https://www.w3schools.com/howto/howto_css_custom_checkbox.asp")

# Find checkbox element
checkbox = driver.find_element(By.CSS_SELECTOR, "input[type='checkbox']")

# Check if checkbox is displayed
print(f"Checkbox displayed: {checkbox.is_displayed()}")

# Check if checkbox is enabled
print(f"Checkbox enabled: {checkbox.is_enabled()}")

# Check if checkbox is selected
print(f"Checkbox selected before click: {checkbox.is_selected()}")

# Click the checkbox to select it
checkbox.click()

# Check if checkbox is selected after click
print(f"Checkbox selected after click: {checkbox.is_selected()}")

# Close the browser
driver.quit()
OutputSuccess
Important Notes

Always wait for elements to load before checking their state to avoid errors.

Use explicit waits in real tests to handle dynamic pages.

is_selected() works mainly for checkboxes, radio buttons, and options.

Summary

Use is_displayed() to check if an element is visible.

Use is_enabled() to check if an element can be interacted with.

Use is_selected() to check if checkboxes or radio buttons are selected.