0
0
Selenium-pythonDebug / FixBeginner · 4 min read

How to Handle Dynamic Elements in Selenium: Fix and Best Practices

Dynamic elements in Selenium change their attributes like IDs or classes, causing locators to fail. Use explicit waits and robust locators like XPath with stable attributes or CSS selectors with partial matches to handle them reliably.
🔍

Why This Happens

Dynamic elements change their properties like id or class every time the page loads or updates. If your test uses a fixed locator for these elements, Selenium cannot find them, causing errors like NoSuchElementException.

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

browser = webdriver.Chrome()
browser.get('https://example.com')

# This locator fails if the element's id changes dynamically
button = browser.find_element(By.ID, 'submit-button-123')
button.click()
Output
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"submit-button-123"}
🔧

The Fix

Use explicit waits to wait for elements to appear and robust locators that rely on stable attributes or partial matches. For example, use XPath with contains() or CSS selectors with starts-with() to handle changing IDs.

python
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

browser = webdriver.Chrome()
browser.get('https://example.com')

wait = WebDriverWait(browser, 10)

# Use XPath with contains() to match dynamic part
button = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@id, 'submit-button')]")))
button.click()
Output
Button clicked successfully without NoSuchElementException
🛡️

Prevention

To avoid issues with dynamic elements, always:

  • Use explicit waits instead of fixed delays.
  • Choose locators based on stable attributes like name, data-* attributes, or visible text.
  • Use XPath functions like contains(), starts-with(), or CSS selectors with partial matches.
  • Keep your locators simple and maintainable.
⚠️

Related Errors

Other common errors when handling dynamic elements include:

  • StaleElementReferenceException: Happens when the element was found but then changed or removed from the page.
  • TimeoutException: Occurs when explicit wait times out waiting for the element.

Fix these by re-finding elements after page updates and increasing wait times or conditions.

Key Takeaways

Use explicit waits to handle elements that load or change dynamically.
Choose locators based on stable attributes or partial matches, not full dynamic IDs.
Avoid fixed delays; rely on Selenium's wait conditions for reliability.
Re-find elements after page updates to prevent stale element errors.
Keep locators simple and maintainable for easier test updates.