is_selected Method

The is_selected() method in Selenium is used to check whether a web element, such as a checkbox, radio button, or option in a dropdown, is currently selected or not. It returns True if the element is selected and False if it is not.

Syntax:

element.is_selected()

Example:

from selenium import webdriver
from selenium.webdriver.common.by import By

# Set up the driver (assuming you're using Chrome)
driver = webdriver.Chrome()

# Open a webpage with website example
driver.get('https://example.com')

# Locate a checkbox or radio button element
checkbox = driver.find_element(By.ID, 'checkbox_id')

# Check if the checkbox is selected
if checkbox.is_selected():
    print("The checkbox is selected.")
else:
    print("The checkbox is not selected.")

# Close the browser
driver.quit()

Example with checkbox selection

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.implicitly_wait(20)
driver.maximize_window()

# Open dummy website on the browser
driver.get('https://sqatools.in/dummy-booking-website/')

# get check element
checkbox_element = driver.find_element(By.XPATH, "//table//tr[2]//input")

# check is_selected status before selecting checkbox
print("is_selected status:", checkbox_element.is_selected()) # False

checkbox_element.click()

# check is_selected status after selecting checkbox
print("is_selected status:", checkbox_element.is_selected() # True

# Close browser
driver.quit()


Explanation:

  • element.is_selected() works primarily for form elements like checkboxes, radio buttons, and options within a <select> dropdown.

  • If the element is selected (checked for a checkbox, selected for a radio button or dropdown option), it returns True. Otherwise, it returns False.

This method is useful when you need to verify the state of form elements before taking further action.