This week Alex looks at Selenium Find Element and a checklist of tips of things to do when an element cannot be found.
What to do when an web element cannot be found? We all had to deal with situations when a test script cannot find an element using code as follows:
WebElement element = driver.findElement(locator);
If findElement() cannot find the element, a NoSuchElementException is generated.
The element is in the page. The locator of the element is correct as well. If findElement() does not work, what else can you do?
1. Use a Different Locator
If you used the element’s id as locator, try a CSS locator instead.
Or an XPATH locator.
2. Synchronize the code with the page
Explicit waits and expected conditions are great when the page loads slowly.
They will keep trying to find the element until the element is available and it has a specific state:
WebDriverWait wait = new WebDriverWait(driver, 30); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(locator));
Make sure that the expected condition matches the element’s status:
presenceOfElementLocated() – if the element is not visible
visibilityOfElementLocated() – if the element is visible
elementToBeClickable() – if the element is clickable
3. Is the element included in a frame?
If the element is in a frame, you need to switch the current driver’s context to the frame before trying to find it:
driver.switchTo().frame("header"); WebElement element = driver.findElement(locator); driver.switchTo().defaultContent();
Remember to switch back from the frame to the main page when you are done interacting with frame elements.
4. Use Javascript
If none of the previous tips works, you can try finding the element by Javascript:
String jsQuery = "function getElement()" + "{var element = document.getElementById('id123'); return element; }; " + "return getElement()"; WebElement element = (WebElement) jsExecutor.executeScript(jsQuery);
5. Reload the page
Sometimes, the element is just in an invalid state and nothing works.
You can reload the page and retry.
This worked for me in a number of occasions.
Have other tips for Selenium Find element?
Please share them in the comments below
About The Author
Alex lives in Vancouver, Canada. He has worked as a software tester since 2005. Alex teaches manual testers test automation with Selenium WebDriver and Java. Alex blogs on testing and automation at http://test-able.blogspot.ca.