QUICK ANSWERNoSuchElementException means Selenium could not find an element with your locator at the moment it looked. The usual causes are a wrong or fragile locator, the element not loaded yet (no wait), the element inside an iframe or another window, or inside a shadow DOM. Fix it with stable locators (ids, data-testid attributes), explicit waits such as WebDriverWait with expected conditions, and switching to the right frame or window first.

Causes and fixes
| Cause | Fix |
|---|---|
| Locator wrong or changed | Check it in DevTools (Ctrl+F in Elements); prefer id or data-testid |
| Page or element still loading | WebDriverWait(driver, 10).until(EC.visibility_of_element_located(...)) |
| Element inside an iframe | driver.switch_to.frame(...), then find; switch_to.default_content() after |
| Opened in a new tab/window | Switch with driver.switch_to.window(handle) |
| Inside a shadow DOM | Use element.shadow_root (Selenium 4) to search inside it |
Dynamic ids (e.g. btn-8273) | Use stable attributes or relative XPath on visible text |
Fix it step by step
- Pause the test at that point and inspect the page in DevTools: is the element really there?
- Test your locator in the browser console:
$$("css selector")or$x("//xpath"). - Replace fixed
time.sleep()with an explicit wait for the exact condition you need (visible, clickable). - Check whether the element is inside an
<iframe>and switch into it. - Ask developers to add
data-testidattributes to important elements; they rarely change. - Take a screenshot and page source on failure so you can see what the browser saw.
Explicit wait example (Python)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-testid=checkout]"))
)
button.click() Locator priority
idordata-testid: best.name, ARIA role and accessible name: good and readable.- Short CSS selectors on stable classes: OK.
- Long absolute XPath like
/html/body/div[3]/div[2]/...: avoid; it breaks with any layout change.
Questions
Should I use implicit or explicit waits?
Prefer explicit waits for specific conditions. Do not mix implicit and explicit waits, because the timeouts can combine in confusing ways.
Is XPath slower than CSS?
The speed difference is small in modern browsers. Stability matters more: choose locators that do not depend on page structure.