Reputation: 1312
I am using selenium java 3.141.59 and testng 6.14.3.
The test page may display like
<tbody>
<tr>
<td class="S_line1">
<strong class="W_f12">82</strong>
<span class="S_txt2">fans</span>
</td>
</tr>
</tbody>
or
<tbody>
<tr>
<td class="S_line1">
<a bpfilter="page_frame" class="t_link S_txt1" href="//xx.com/p/1003061291477752/follow?from=page_100306&wvr=6&mod=headfollow#place">
<strong class="W_f12">170</strong>
<span class="S_txt2">fans</span>
</a>
</td>
</tr>
</tbody>
If "fans" have a href link,then I will click "fans" link. If not I will skip this step and continue to do others.
ExpectedConditions.presenceOfElementLocated is not availabe to this situation, because it will throw exeception when not finding href link and stop the test.
Upvotes: 2
Views: 4263
Reputation: 3384
Following code first finds all the <a>
tags within the table, and one by one if tag have href
, will click them:
List<WebElement> allAnchorElements = driver.findElements(By.xpath("//table//td[@class='S_line1']/a"));
for(WebElement currElem : allAnchorElements ){
if(currElem.getAttribute("href")){
currElem.click();
}
}
Upvotes: 1
Reputation: 1689
For checking the node href
is present or not, you can use the below XPath to identify the a
node because href
is present inside of a
(I'm assuming that the class is unique here, if not then use some other locator with //a
appending at the end) :
String xpath = "//td[@class=\"S_line1\"]/a"
You can check for it's presence like below :
List<WebElement> hrefs = driver.findElements(By.xpath(xpath));
if(hrefs.size() > 0) {
System.out.println("=> The href is present...");
hrefs.get(0).click();
} else {
System.out.println("=> The href is not present...");
}
The above code will not throw any error if the href
is not there. So you don't need to handle any exceptions there.
I hope it helps...
Upvotes: 3
Reputation: 5204
You are looking for only the fans
element that has the href
...
The best way I can think of is to use By.linkText()
.
In your case:
try{
WebElement link = driver.findElement(By.linkText("fans"));
System.out.println(link.getAttribute("href"));
link.click();
}
catch(NoSuchElementException e){
System.out.println(e);
}
Hope this helps you!
Upvotes: 0