Reputation: 63
Currently I know you can search for web elements on xpath with this syntax:
driver.findElement(By.xpath("//*[text()='text to be found']"));
Is there anyway I can search for elements from a variable String? I would like to be able to make a method like this:
public boolean nameExists( String name ) {
if (driver.findElement(By.xpath("//*[text()= name ]")) )
return true;
else
return false;
}
Upvotes: 0
Views: 1315
Reputation: 6551
You could do something like this:
public boolean nameExists(String name) {
return driver.findElements(By.xpath("//*[text()='" + name + "']")).size() != 0;
}
Remember that findElement
returns a WebElement
not a boolean
. Also, if the given element does not exist, Selenium will throw a NoSuchElementException
.
Instead, we can utilize findElements
to find all the WebElement
s with the given String name
from your XPath. If the returned List<WebElement>
contains any values (.size() != 0
), this means at least one WebElement
with the given name
exists.
Upvotes: 3