ElementNotFoundError
browser_use.exceptions.ElementNotFoundError
Stack trace
browser_use.exceptions.ElementNotFoundError: No element found for selector '#submit-button'
File "app.py", line 42, in run_browser_task
element = browser.page.query_selector('#submit-button') # ElementNotFoundError here
File "browser_use/page.py", line 88, in query_selector
raise ElementNotFoundError(f"No element found for selector '{selector}'") Why it happens
This error occurs when the browser automation script tries to find an element using a CSS or XPath selector that does not exist on the current page. It can happen if the page structure changed, the selector is incorrect, or the element is dynamically loaded but not yet present.
Detection
Add logging before selector queries to verify the page URL and HTML content, and catch ElementNotFoundError exceptions to log the missing selector and page state before failure.
Causes & fixes
The CSS or XPath selector is misspelled or incorrect.
Verify and correct the selector string to exactly match the element's identifier on the page.
The element is dynamically loaded and not present at the time of query.
Add explicit waits or retries to wait for the element to appear before querying.
The page URL or content is different than expected (e.g., redirected or error page).
Confirm the browser navigated to the correct URL and the page loaded successfully before querying selectors.
Using a selector that matches multiple elements but expecting one.
Use a more specific selector or query all matching elements and handle them accordingly.
Code: broken vs fixed
from browser_use import Browser
browser = Browser()
browser.page.goto('https://example.com')
element = browser.page.query_selector('#submit-button') # ElementNotFoundError here
print(element.text_content()) import os
from browser_use import Browser
browser = Browser()
browser.page.goto('https://example.com')
# Wait for element to appear before querying
browser.page.wait_for_selector('#submit-button', timeout=5000)
element = browser.page.query_selector('#submit-button') # Fixed: wait added
print(element.text_content()) Workaround
Wrap the selector query in try/except ElementNotFoundError, then log the page HTML or take a screenshot for debugging and optionally retry after a delay.
Prevention
Use explicit waits for elements to load and verify page navigation success before querying selectors to avoid missing elements due to timing or navigation issues.