How to click a href link using Selenium?

SeleniumAutomation TestingTesting Tools

We can click a href link with Selenium webdriver. There are multiple ways to achieve this. First of all we need to identify the link with the help of the locators like link text and partial link text.

The link text locator identifies the element whose text matches with text enclosed within the anchor tag. The partial link text locator identifies the element whose text matches partially with the text enclosed within the anchor tag. Once the linkwith href is identified we need to apply the click() method to it.

Let's try to click the link Privacy Policy on the page.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ClickLinkText{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with link text then apply click()
      WebElement p=driver.findElement(By.linkText("Privacy Policy"));
      p.click();
      System.out.println("Page title after link click : " + driver.getTitle());
      driver.close();
   }
}

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ClickPartialLinkText{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with link text then apply click()
      WebElement p=driver.findElement(By.partialLinkText("Privacy"));
      p.click();
      System.out.println("Page title after link click : " +   driver.getTitle());
      driver.close();
   }
}

Output

raja
Published on 18-Sep-2020 15:41:31
Advertisements