Checking element state (displayed, enabled, selected) in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import unittest class TestElementStates(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com/sample-form') self.wait = WebDriverWait(self.driver, 10) def test_checkbox_and_button_states(self): driver = self.driver wait = self.wait # Wait for checkbox to be visible checkbox = wait.until(EC.visibility_of_element_located((By.ID, 'subscribe-newsletter'))) # Assert checkbox is displayed self.assertTrue(checkbox.is_displayed(), 'Checkbox should be displayed') # Assert checkbox is enabled self.assertTrue(checkbox.is_enabled(), 'Checkbox should be enabled') # Assert checkbox is not selected initially self.assertFalse(checkbox.is_selected(), 'Checkbox should not be selected initially') # Click checkbox to select it checkbox.click() # Assert checkbox is selected after clicking self.assertTrue(checkbox.is_selected(), 'Checkbox should be selected after clicking') # Wait for submit button to be visible and enabled submit_btn = wait.until(EC.element_to_be_clickable((By.ID, 'submit-btn'))) # Assert submit button is displayed self.assertTrue(submit_btn.is_displayed(), 'Submit button should be displayed') # Assert submit button is enabled self.assertTrue(submit_btn.is_enabled(), 'Submit button should be enabled') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
This test script uses Python's unittest framework with Selenium WebDriver.
setUp() opens the browser and navigates to the sample form page.
We use WebDriverWait with expected_conditions to wait until elements are visible or clickable before interacting.
We locate the checkbox by its ID and check if it is displayed, enabled, and not selected initially using is_displayed(), is_enabled(), and is_selected() methods.
Then we click the checkbox and verify it becomes selected.
Similarly, we locate the submit button and verify it is displayed and enabled.
tearDown() closes the browser after the test.
This structure ensures reliable and readable tests following best practices.
Now add data-driven testing to check checkbox selection state with 3 different initial states (selected, not selected, disabled).