Introduction
While automating web applications, Selenium interacts with various web elements such as text fields, buttons, checkboxes, and dropdowns. However, there are situations where an element exists on the webpage and is visible, but Selenium cannot perform the requested action because the element is not in an appropriate state.
When Selenium attempts such an invalid operation, it raises an InvalidElementStateException.
This exception commonly occurs when interacting with read-only fields, disabled elements, or when attempting operations that are not supported in the element’s current state. Understanding why this exception occurs helps automation engineers write more reliable and maintainable Selenium scripts.
In this tutorial, you will learn what InvalidElementStateException is, why it occurs, how to handle it properly, practical examples, common mistakes, best practices, and frequently asked interview questions.
What is InvalidElementStateException?
InvalidElementStateException is raised when Selenium attempts to perform an operation that is not valid for the element’s current state.
For example:
Locate Element
│
▼
Element Exists?
/ \
No Yes
│ │
▼ ▼
Exception Can Selenium Perform
Raised the Requested Action?
│
Yes/No
/ \
Yes No
│ │
▼ ▼
Continue Raise
Execution InvalidElementStateException
Although the element exists and is visible, Selenium cannot perform the requested action because the element does not allow it.
Why Does InvalidElementStateException Occur?
Some common reasons include:
Attempting to clear a read-only input field.
Trying to modify disabled elements.
Performing unsupported operations on an element.
Interacting with elements in an invalid state.
Application restrictions implemented using HTML attributes such as
readonlyordisabled.Dynamic webpage behavior that temporarily changes an element’s state.
Practical Example
The following example dynamically creates a read-only text field using JavaScript. Selenium successfully locates the element but cannot clear its value because the field is marked as read-only.
As a result, Selenium raises InvalidElementStateException.
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import (
InvalidElementStateException,
)
# Topic: InvalidElementStateException
# Practice site: https://www.testmuai.com/selenium-playground/
# Run: pytest -s 61_examples/test_06_invalid_element_state_exception.py
#
# InvalidElementStateException is raised when an action is not valid for the
# element's current state, such as clearing a read-only input field.
def test_invalid_element_state_exception():
driver = webdriver.Chrome()
try:
driver.get(
"https://www.testmuai.com/selenium-playground/"
)
driver.execute_script(
"""
const readonly = document.createElement('input');
readonly.id = 'readonly-field';
readonly.type = 'text';
readonly.value = 'locked';
readonly.setAttribute('readonly', 'readonly');
document.body.appendChild(readonly);
"""
)
with pytest.raises(
InvalidElementStateException
):
driver.find_element(
By.ID,
"readonly-field"
).clear()
finally:
driver.quit()
Output
Chrome browser launched successfully.
Website opened successfully.
Read-only input field created successfully.
Selenium located the element successfully.
Attempting to clear the field.
InvalidElementStateException raised successfully.
Exception handled successfully.
Test Executed Successfully.
Note: The exception is expected in this example. PyTest treats the test as successful because
pytest.raises()explicitly verifies thatInvalidElementStateExceptionis raised.
Understanding the Code
Import Required Modules
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import (
InvalidElementStateException,
)
Imports:
Selenium WebDriver.
Locator strategies.
InvalidElementStateException.PyTest for exception validation.
Launch Chrome Browser
driver = webdriver.Chrome()
Creates a new Chrome browser session.
Open the Website
driver.get(
"https://www.testmuai.com/selenium-playground/"
)
Opens the Selenium Playground website.
Create a Read-Only Input Field
driver.execute_script(
"""
JavaScript Code
"""
)
The JavaScript code:
Creates a text field.
Assigns it the ID
readonly-field.Sets its default value.
Marks it as read-only.
Adds it to the webpage.
Since the element is read-only, users cannot modify its value.
Attempt to Clear the Field
driver.find_element(
By.ID,
"readonly-field"
).clear()
Although Selenium successfully locates the element, it cannot clear the field because its current state does not allow modifications.
Verify the Exception
with pytest.raises(
InvalidElementStateException
):
driver.find_element(
By.ID,
"readonly-field"
).clear()
pytest.raises() verifies that Selenium raises the expected exception.
If the exception occurs successfully, the test passes.
Close the Browser
driver.quit()
Closes all browser windows and properly ends the WebDriver session.
Execution Flow
Launch Browser
│
▼
Open Website
│
▼
Create Read-Only Element
│
▼
Locate Element
│
▼
Attempt Invalid Operation
│
▼
Is the Action Allowed?
/ \
Yes No
│ │
▼ ▼
Continue Raise
Execution InvalidElementStateException
│
▼
Verify Exception Using PyTest
│
▼
Close Browser
Automation Testing Example
Suppose an application displays an order number field that users are not allowed to modify.
<input
type="text"
value="ORD-1001"
readonly>
If Selenium attempts:
order_number.clear()
Selenium raises:
InvalidElementStateException
because the field is intentionally protected from modifications.
Real-World Example
Many enterprise applications contain:
Read-only fields.
Disabled buttons.
Locked input controls.
Permission-based UI components.
For example:
User Profile Page
│
▼
Employee ID Field
(Read-Only)
│
▼
Selenium Attempts Modification
│
▼
InvalidElementStateException
These restrictions are frequently implemented to prevent unauthorized modifications.
Common Mistakes Beginners Make
Attempting to Modify Read-Only Fields
Incorrect
username.clear()
without verifying whether the field is editable.
Better
username.get_attribute("readonly")
Always verify whether an element is editable before performing modification operations.
Confusing It with ElementNotInteractableException
Many beginners assume both exceptions are identical.
However:
ElementNotInteractableException
≠
InvalidElementStateException
The differences are:
ElementNotInteractableException
Element exists but cannot
currently receive interactions.
--------------------------------
InvalidElementStateException
Element exists and may be
visible, but the requested
operation is not allowed.
Understanding this distinction simplifies debugging significantly.
Ignoring Element Attributes
Always inspect important attributes such as:
readonly
disabled
hidden
aria-disabled
before interacting with web elements.
Best Practices
Verify that elements are editable before modifying them.
Understand the application’s business rules.
Use explicit waits when element states change dynamically.
Inspect important HTML attributes before performing interactions.
Avoid forcing interactions that violate application behavior.
Synchronize Selenium properly with dynamic webpages.
Conclusion
InvalidElementStateException occurs whenever Selenium attempts to perform an operation that is not valid for an element’s current state. Read-only and disabled elements are among the most common causes of this exception.
Understanding how applications manage element states significantly improves automation reliability and helps engineers write more maintainable Selenium frameworks.
Mastering Selenium exceptions is an essential skill for both automation testing and technical interviews.
Frequently Asked Questions (FAQs)
What is InvalidElementStateException?
It is raised when Selenium attempts to perform an invalid operation on an element based on its current state.
What causes this exception?
Common causes include:
Read-only elements.
Disabled controls.
Unsupported element interactions.
Dynamic state changes.
Can read-only fields cause this exception?
Yes.
Attempting to modify or clear read-only fields commonly raises InvalidElementStateException.
What is the difference between ElementNotInteractableException and InvalidElementStateException?
ElementNotInteractableExceptionoccurs when Selenium cannot interact with an element.InvalidElementStateExceptionoccurs when Selenium can locate the element, but the requested operation is not valid for its current state.
Why do we use pytest.raises() in this example?
pytest.raises() verifies that Selenium raises the expected exception, allowing us to validate Selenium’s behavior during testing.
Key Takeaways
InvalidElementStateExceptionoccurs when Selenium performs an operation that is not valid for an element’s current state.Read-only and disabled elements are common causes of this exception.
Always verify whether an element is editable before modifying it.
Understanding HTML element attributes significantly improves debugging.
pytest.raises()can be used to validate expected exceptions during testing.Proper synchronization and element validation improve automation framework reliability.
Understanding Selenium exceptions simplifies real-world test failure analysis.
InvalidElementStateExceptionis an important Selenium automation and interview topic.
