selenium how to know if one element has a href link or not,if not continue the test

Venus :

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&amp;wvr=6&amp;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.

Ali CSE :

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...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145654&siteId=1