I'm trying to check if an element exists before I can execute this line:
driver.findElement(webdriver.By.id('test'));
This throws an error "no such element" if the id test
doesn't exist in the document, even in a try
-block.
I've found answers for Java, where you can check if the size is 0, but in node-js this throws an error before I can check the size.
throw error;
^
NoSuchElementError: no such element
We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.
isDisplayed() is the method used to verify a presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
We can check if some text exists or not in a page with Selenium. There are more than one ways to find it. We can use the getPageSource() method to fetch the full page source and then verify if the text exists there. This method returns content in the form of string.
You can leverage the optional error handler argument of then()
.
driver.findElement(webdriver.By.id('test')).then(function(webElement) {
console.log('Element exists');
}, function(err) {
if (err.state && err.state === 'no such element') {
console.log('Element not found');
} else {
webdriver.promise.rejected(err);
}
});
I couldn't find it explicitly stated in the documentation, but determined this from the function definition in webdriver/promise.js
in the selenium-webdriver
module source:
/**
* Registers a callback on this Deferred.
* @param {Function=} opt_callback The callback.
* @param {Function=} opt_errback The errback.
* @return {!webdriver.promise.Promise} A new promise representing the result
* of the callback.
* @see webdriver.promise.Promise#then
*/
function then(opt_callback, opt_errback) {
The accepted answer did not work for me fully, though some parts of it were helpful. Arthur Weborg's answer above worked for me, though some parts caused issues: https://stackoverflow.com/a/45273140/5648143
My typical use case for "checking if element exists" is when I want to click the element, only if it exists, since if it doesn't exist, it crashes the program due to the error. All I want is for the application to note that it doesn't exist, and move on. So what I do is:
await driver.findElement(By.id("test")).then(found => {
driver.findElement(By.id("test")).click()
}, error => {
if (error instanceof webdriver.error.NoSuchElementError) {
console.log('Element not found.');
}
});
Just a simple console log, and moves on with the rest of the program like I wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With