Bird
Raised Fist0
Selenium Pythontesting~15 mins

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

Choose your learning style10 modes available
Overview - Checking element state (displayed, enabled, selected)
What is it?
Checking element state means verifying if a web page element is visible (displayed), can be interacted with (enabled), or is chosen (selected). These checks help ensure your automated tests interact only with elements ready for action. For example, a button might be visible but disabled, so clicking it would fail. Selenium provides simple methods to check these states before performing actions.
Why it matters
Without checking element states, tests might try to click invisible or disabled buttons, causing errors and unreliable results. This wastes time and hides real problems in the application. Proper state checks make tests stable and trustworthy, saving developers from chasing false failures and improving user experience by catching UI issues early.
Where it fits
Before this, learners should know basic Selenium commands to locate elements and perform actions like click or send keys. After mastering element state checks, learners can move on to advanced waits, handling dynamic pages, and building robust test suites that adapt to changing UI conditions.
Mental Model
Core Idea
Before interacting with a web element, always confirm it is visible, enabled, and selected as needed to avoid errors and ensure meaningful test actions.
Think of it like...
It's like checking a door before you open it: you look if it's there (displayed), unlocked (enabled), and if it's already open or closed (selected) to decide your next move safely.
┌───────────────┐
│ Web Element   │
├───────────────┤
│ Displayed?    │──Yes──┐
│ Enabled?      │──Yes──┼──> Interact
│ Selected?     │──Depends
└───────────────┘
If any check fails, interaction is unsafe.
Build-Up - 6 Steps
1
FoundationUnderstanding Element Visibility
🤔
Concept: Learn how to check if an element is visible on the page using Selenium.
In Selenium, the method is_displayed() returns True if the element is visible to the user. For example: button = driver.find_element(By.ID, 'submit') print(button.is_displayed()) # True if visible, False if hidden This helps avoid interacting with hidden elements that cause errors.
Result
Output is True if the element is visible, False otherwise.
Understanding visibility prevents errors from trying to click or type into elements that users cannot see or interact with.
2
FoundationChecking If Element Is Enabled
🤔
Concept: Learn to verify if an element is enabled and ready for interaction.
Use is_enabled() to check if an element can be used. For example: input_field = driver.find_element(By.NAME, 'email') print(input_field.is_enabled()) # True if enabled, False if disabled Disabled elements often appear greyed out and cannot be clicked or typed into.
Result
Output is True if the element is enabled, False if disabled.
Knowing if an element is enabled helps avoid test failures caused by trying to use inactive controls.
3
IntermediateDetermining Element Selection State
🤔Before reading on: do you think is_selected() applies only to checkboxes and radio buttons, or to all elements? Commit to your answer.
Concept: Learn how to check if an element like a checkbox or radio button is selected using is_selected().
The is_selected() method returns True if the element is selected (checked), False otherwise. Example: checkbox = driver.find_element(By.ID, 'agree') print(checkbox.is_selected()) # True if checked This is useful to verify user choices or toggle states.
Result
Output is True if the element is selected, False if not.
Understanding selection state is key to validating user inputs and UI toggles in tests.
4
IntermediateCombining State Checks Before Actions
🤔Before reading on: do you think checking only visibility is enough before clicking an element? Commit to your answer.
Concept: Learn to combine displayed, enabled, and selected checks to safely interact with elements.
Before clicking or typing, check all relevant states: button = driver.find_element(By.ID, 'submit') if button.is_displayed() and button.is_enabled(): button.click() else: print('Button not ready for interaction') This prevents errors and flaky tests.
Result
Actions only happen if the element is visible and enabled, avoiding exceptions.
Combining checks ensures tests only act on elements ready for interaction, improving reliability.
5
AdvancedHandling Dynamic Element States with Waits
🤔Before reading on: do you think immediate state checks always work on dynamic pages? Commit to your answer.
Concept: Learn to use Selenium waits to handle elements whose states change dynamically after page load.
Sometimes elements appear or become enabled after some delay. Use WebDriverWait with expected_conditions: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) button = wait.until(EC.element_to_be_clickable((By.ID, 'submit'))) button.click() This waits up to 10 seconds for the button to be visible and enabled.
Result
Test waits for element readiness, reducing flaky failures on slow or dynamic pages.
Using waits with state checks handles real-world delays and asynchronous UI changes gracefully.
6
ExpertSurprising Behavior of is_displayed() and Shadow DOM
🤔Before reading on: do you think is_displayed() works the same inside Shadow DOM elements? Commit to your answer.
Concept: Discover how is_displayed() behaves differently with Shadow DOM elements and how to handle it.
Selenium's is_displayed() may not correctly detect visibility inside Shadow DOM because it doesn't pierce shadow boundaries by default. To check visibility inside Shadow DOM, you must access shadow roots explicitly: shadow_host = driver.find_element(By.CSS_SELECTOR, 'shadow-host') shadow_root = shadow_host.shadow_root inner_element = shadow_root.find_element(By.CSS_SELECTOR, '.inner') print(inner_element.is_displayed()) Without this, is_displayed() might return False even if visible.
Result
Proper visibility checks inside Shadow DOM require special handling, else tests may falsely fail.
Knowing Shadow DOM limits of is_displayed() prevents subtle bugs in modern web apps using web components.
Under the Hood
Selenium's is_displayed() checks the element's CSS properties like display, visibility, and opacity, and whether it is within the viewport. is_enabled() checks the HTML disabled attribute and other factors that prevent interaction. is_selected() checks the selected or checked state for input elements. These methods query the browser's rendering engine via WebDriver commands, reflecting the current UI state.
Why designed this way?
These methods abstract complex browser internals into simple boolean checks to make test writing easier and more reliable. Directly querying CSS or attributes would be error-prone and inconsistent across browsers. Selenium standardizes these checks to work uniformly, hiding browser differences and simplifying test logic.
┌───────────────┐
│ Selenium Test │
└──────┬────────┘
       │ calls
┌──────▼────────┐
│ WebDriver API │
└──────┬────────┘
       │ queries
┌──────▼────────┐
│ Browser Engine│
│ (CSS, DOM)    │
└──────┬────────┘
       │ returns
┌──────▼────────┐
│ Element State │
│ (displayed,   │
│ enabled,      │
│ selected)     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does is_displayed() return True for elements hidden behind others? Commit to yes or no.
Common Belief:is_displayed() returns True if the element exists in the DOM, regardless of overlap or visibility.
Tap to reveal reality
Reality:is_displayed() returns False if the element is hidden by CSS or overlapped so it is not visible to the user.
Why it matters:Assuming is_displayed() ignores overlap can cause tests to click invisible elements, leading to false passes or errors.
Quick: Does is_enabled() guarantee an element can be clicked? Commit to yes or no.
Common Belief:If is_enabled() returns True, the element can always be clicked successfully.
Tap to reveal reality
Reality:is_enabled() only checks if the element is not disabled; other factors like overlays or page state can still block clicks.
Why it matters:Relying solely on is_enabled() can cause flaky tests when elements are technically enabled but not interactable.
Quick: Does is_selected() apply to all HTML elements? Commit to yes or no.
Common Belief:is_selected() works for any element to check if it is chosen or active.
Tap to reveal reality
Reality:is_selected() only applies to input elements like checkboxes, radio buttons, and options; other elements always return False.
Why it matters:Misusing is_selected() on unsupported elements leads to incorrect test logic and missed bugs.
Quick: Does is_displayed() work the same inside Shadow DOM? Commit to yes or no.
Common Belief:is_displayed() works uniformly for all elements, including those inside Shadow DOM.
Tap to reveal reality
Reality:is_displayed() may fail to detect visibility inside Shadow DOM without accessing shadow roots explicitly.
Why it matters:Ignoring Shadow DOM specifics causes false negatives in tests for modern web components.
Expert Zone
1
is_displayed() depends on multiple CSS properties and layout calculations, so small style changes can unexpectedly affect visibility results.
2
is_enabled() does not consider JavaScript event handlers that might block interaction, so an element can be enabled but still unclickable.
3
Combining state checks with explicit waits is essential for stable tests on dynamic web pages where element states change asynchronously.
When NOT to use
Avoid relying solely on these state checks for complex UI interactions involving animations, overlays, or custom controls. Instead, use advanced user interaction APIs like Actions chains or JavaScript execution to verify and interact with elements.
Production Patterns
In real-world test suites, testers wrap state checks inside reusable helper functions with waits to handle flaky elements. They also log detailed state info on failures to diagnose UI issues quickly. For Shadow DOM, accessing shadow roots is standard practice to ensure accurate state detection.
Connections
Explicit Waits in Selenium
Builds-on
Understanding element state checks is essential before applying explicit waits that wait for those states, making tests more reliable.
User Interface Accessibility
Related concept
Checking if elements are visible and enabled aligns with accessibility principles ensuring users can perceive and interact with UI components.
Quality Control in Manufacturing
Analogous process
Just like checking if a product is visible, functional, and selected for shipment, verifying element states ensures only ready UI parts are used, preventing defects.
Common Pitfalls
#1Trying to click an element without checking if it is visible or enabled.
Wrong approach:button = driver.find_element(By.ID, 'submit') button.click()
Correct approach:button = driver.find_element(By.ID, 'submit') if button.is_displayed() and button.is_enabled(): button.click() else: print('Button not ready')
Root cause:Assuming elements are always ready to interact leads to exceptions when elements are hidden or disabled.
#2Using is_selected() on elements that do not support selection.
Wrong approach:div = driver.find_element(By.ID, 'content') print(div.is_selected()) # Incorrect use
Correct approach:checkbox = driver.find_element(By.ID, 'agree') print(checkbox.is_selected()) # Correct use
Root cause:Misunderstanding which elements support selection causes wrong test logic and false results.
#3Not waiting for element state changes on dynamic pages.
Wrong approach:button = driver.find_element(By.ID, 'submit') button.click() # May fail if button not ready
Correct approach:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) button = wait.until(EC.element_to_be_clickable((By.ID, 'submit'))) button.click()
Root cause:Ignoring asynchronous UI updates causes flaky tests and intermittent failures.
Key Takeaways
Always check if a web element is displayed and enabled before interacting to avoid test errors.
Use is_selected() only for elements that support selection like checkboxes and radio buttons.
Combine element state checks with explicit waits to handle dynamic page behavior reliably.
Understand that is_displayed() depends on CSS and layout, and may behave differently inside Shadow DOM.
Proper element state verification makes automated tests stable, trustworthy, and easier to maintain.

Practice

(1/5)
1. Which Selenium method checks if a web element is visible on the page?
easy
A. is_enabled()
B. is_visible()
C. is_selected()
D. is_displayed()

Solution

  1. Step 1: Understand the purpose of is_displayed()

    This method returns True if the element is visible to the user on the page.
  2. Step 2: Compare with other methods

    is_enabled() checks if the element can be interacted with, is_selected() checks selection state, and is_visible() is not a valid Selenium method.
  3. Final Answer:

    is_displayed() -> Option D
  4. Quick Check:

    Visibility check = is_displayed() [OK]
Hint: Visible? Use is_displayed() method [OK]
Common Mistakes:
  • Confusing is_enabled() with visibility
  • Using is_selected() for visibility
  • Assuming is_visible() exists in Selenium
2. Which of the following is the correct syntax to check if a checkbox element is selected in Selenium Python?
easy
A. checkbox.is_selected()
B. checkbox.selected()
C. checkbox.isSelected()
D. checkbox.selected

Solution

  1. Step 1: Recall Selenium Python method names

    In Selenium Python, the method to check selection is is_selected() with underscores and parentheses.
  2. Step 2: Identify incorrect syntax

    selected() and selected are invalid; isSelected() is Java style, not Python.
  3. Final Answer:

    checkbox.is_selected() -> Option A
  4. Quick Check:

    Check selected? Use is_selected() [OK]
Hint: Use is_selected() with parentheses for selection check [OK]
Common Mistakes:
  • Using Java method style isSelected() in Python
  • Omitting parentheses after method name
  • Using property 'selected' instead of method
3. Given the following code snippet, what will be the output if the button is visible but disabled?
button = driver.find_element(By.ID, 'submit')
print(button.is_displayed())
print(button.is_enabled())
medium
A. True\nFalse
B. False\nTrue
C. True\nTrue
D. False\nFalse

Solution

  1. Step 1: Understand is_displayed() output

    Since the button is visible, is_displayed() returns True.
  2. Step 2: Understand is_enabled() output

    The button is disabled, so is_enabled() returns False.
  3. Final Answer:

    True\nFalse -> Option A
  4. Quick Check:

    Visible = True, Enabled = False [OK]
Hint: Visible True, Enabled False if button disabled [OK]
Common Mistakes:
  • Assuming disabled means not visible
  • Mixing up is_displayed() and is_enabled() results
  • Expecting both to be True for visible button
4. You wrote this code to check if a checkbox is selected:
checkbox = driver.find_element(By.NAME, 'agree')
if checkbox.selected():
    print('Selected')
else:
    print('Not selected')
What is the error here?
medium
A. Print statements should be inside quotes
B. Missing parentheses after find_element
C. selected() is not a valid method; should use is_selected()
D. Checkbox element locator is incorrect

Solution

  1. Step 1: Check method name for selection

    The correct method to check selection in Selenium Python is is_selected(), not selected().
  2. Step 2: Verify other code parts

    Parentheses after find_element are correct, locator looks valid, and print statements are properly quoted.
  3. Final Answer:

    selected() is not a valid method; should use is_selected() -> Option C
  4. Quick Check:

    Use is_selected() method for checkbox state [OK]
Hint: Use is_selected(), not selected() method [OK]
Common Mistakes:
  • Using selected() instead of is_selected()
  • Confusing method names with Java syntax
  • Ignoring method parentheses
5. You want to write a test that clicks a button only if it is visible and enabled. Which code snippet correctly checks these conditions before clicking?
button = driver.find_element(By.ID, 'save')
hard
A. if button.is_displayed() or button.is_enabled(): button.click()
B. if button.is_displayed() and button.is_enabled(): button.click()
C. if button.is_selected() and button.is_enabled(): button.click()
D. if button.is_enabled(): button.click()

Solution

  1. Step 1: Identify conditions for clicking

    The button must be visible (is_displayed()) and enabled (is_enabled()) to be safely clicked.
  2. Step 2: Analyze each option

    if button.is_displayed() and button.is_enabled(): button.click() uses both conditions with 'and', which is correct. if button.is_selected() and button.is_enabled(): button.click() wrongly uses is_selected() which is for checkboxes/radios. if button.is_displayed() or button.is_enabled(): button.click() uses 'or' which may click if only one condition is true. if button.is_enabled(): button.click() checks only enabled, ignoring visibility.
  3. Final Answer:

    if button.is_displayed() and button.is_enabled():\n button.click() -> Option B
  4. Quick Check:

    Click only if visible AND enabled [OK]
Hint: Use and with is_displayed() and is_enabled() before click [OK]
Common Mistakes:
  • Using or instead of and for conditions
  • Checking is_selected() for buttons
  • Ignoring visibility check before clicking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard