How to find an element using the “Link Text/Partial Link Text” in Selenium?

SeleniumAutomation TestingTesting Tools

We can find an element using the link text or the partial link text in Selenium webdriver. Both these locators can only be applied to elements with the anchor tag.

The link text locator matches the text inside the anchor tag. The partial link text locator matches the text inside the anchor tag partially. NoSuchElementException shall be thrown for both these locators if there is no matching element.

Syntax

WebElement n =driver.findElement(By.partialLinkText("Coding"));
WebElement l =driver.findElement(By.linkText("Coding Ground"));

Let us find the below highlighted element CODING GROUND on the page −

Example

Code Implementation with linkText

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LnkTxt{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/online_dev_tools.htm");
      // identify element with link text
      WebElement n =driver.findElement(By.linkText("CODING GROUND"));
      n.click();
      System.out.println("Current page title : " + driver.getTitle());
      driver.quit();
   }
}

Code Implementation with partialLinkText

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class PartialLnkTxt{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/online_dev_tools.htm");
      // identify element with partial link text
      WebElement m = driver.findElement(By.partialLinkText("CODING"));
      m.click();
      System.out.println("Current page title : " + driver.getTitle());
      driver.quit();
   }
}

Output

raja
Published on 06-Apr-2021 10:38:45
Advertisements