简体   繁体   中英

Finding a link with a non-breaking space inside it with Selenium

I'm getting better finding links without any id or name but this one has me stumped and a Google search hasn't helped. I'm trying to click on a link using Selenium webdriver in Java.

 <a class="mainleftlinks" onclick="return TrackChanges();" href="/chcfweb/sbc/administration/aac/leftlinks.do?linkid=040000" styleclass="mainleftlinks">&nbsp;&nbsp;Administrative &nbsp;&nbsp;Claiming</a>

Not sure what those nbsp things are. If you look at the application the link/button looks like this:

 Administrative
 Claiming

Not sure how to format the cssSelector, use xpath to find this? Use something else? I'm stumped. Any help greatly appreciated!

The &nbsp; is a non breakable space and it needs to be included. Here are multiple ways to get your link by text:

// by link text with 2 spaces at the begining and 3 spaces in the middle
WebElement ele1 = driver.findElement(By.linkText("  Administrative   Claiming"));

// by xpath with the caracter code of `&nbsp;`
WebElement ele2 = driver.findElement(By.xpath("//a[.='\u00A0\u00A0Administrative \u00A0\u00A0Claiming']"));

// by xpath by removing the `&nbsp;`
WebElement ele3 = driver.findElement(By.xpath("//a[translate(.,'\u00A0','')='Administrative Claiming']"));

nbsp is an encoded whitespace. You don't see it in the link because it gets automatically converted into ' '. I'm not sure I've understood your question, but you can easily get that field by id or class name:

driver.findElement(By.id(yourId));

EDIT

Alternatively you could get that by class name:

List<WebElement> elements = driver.findElements(By.className(className));

Notice that this will get you back all the elements of that class. Then you can iterate them and check the text to match your case.

Use xpath contains. Maybe something along the lines of

driver.findElement(By.xpath("//*[contains(., 'Administrative') and contains(., 'Claiming')]"));

@PeterCook if you want you could use the onclick. Try

driver.findElement(By.cssSelector("*[onclick='return TrackChanges();']")).click

Do you need to use the text?

driver.findElement(By.xpath("//*[contains(translate(., '\u00A0', ' '), 'Administrative Claiming')]"));

有关解释,请在此处查看我的答案

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM