I'm trying to find a given link WebElement by partial link text but I want to leverage starts-with
to make it more robust. The WebElement I am trying to find is the second one in the following list ...
<a id="" class="" onmouseout="" href="some.random.href" target="" onmousedown="" onmouseup="" onmouseover="" title="" onclick=""> nsfoobar:80</a>
<a id="" class="" onmouseout="" href="some.other.random.href" target="" onmousedown="" onmouseup="" onmouseover="" title="" onclick=""> sfoobar:443</a>
I thought finding it by xpath and starts-with
would be a good approach but it's throwing a NoSuchElementException ...
sfoobarXpath = "//a[starts-with(.,' sfoobar:')]";
driver.findElement(By.xpath(sfoobarXpath)).click();
Any idea what I'm doing wrong here?
EDIT1: Edited example to better illustrate problem
EDIT2: I need to be able to find this WebElement without knowledge of the text of the other WebElement; in my actual environment, there can be any number of these link elements and they're subject to change.
Try this xpath expression:
**//a[normalize-space(substring-before(.,':'))='sfoobar']**
substring-before(.,':')
retrieves the text content of the WebElement before the colon character.
normalize-space()
removes the leading whitespace from the WebElement.
Use the xpath contains()
function
//a[contains(text(),'sfoobar')]
Edit
According to the OP's edit
//a[contains(text(),'sfoobar')and not(contains(text(),'nsfoobar'))]
As per the html you have given in your question, and your requirement of using starts-with
, you can try the below xpath:
//a[not(starts-with(text(),' n'))]
Note:- The above will select the link that doesn't have innerHTML or text starting with " n" (there is a space before 'n' as is given in the html so provided) .
I ended up just finding all the link elements by partial link text and iterating through that list to find the one with substring before the :
that exactly equals sfoobar
. It's not the most elegant solution but it seems to work ...
List<WebElement> links = driver.findElements(By.partialLinkText("sfoobar"));
if(links.isEmpty()) {
throw new RuntimeException("Cannot find any links.");
}
else {
for(WebElement link:links) {
if(StringUtils.substringBefore(link.getText(),":").equals("sfoobar")) {
link.click();
break;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.