Selenium Click Link By href Value

SeleniumAutomation TestingTesting Tools

We can click a link by href value with Selenium webdriver. To identify the link with the href attribute we can take the help of the locators xpath or css selector.

We shall use the findElement method and pass By.xpath or By.cssSelector as a parameter to this method. Let us investigate the html code of the link Privacy Policy in the below image with the anchor tag having a href attribute as /about/about_privacy.htm.

Code Implementation

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 FirstAssign{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "chromedriver");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get
      ("https://www.tutorialspoint.com/about/about_privacy.htm");
      //identify element with href value in CSS
      WebElement elm = driver
      .findElement(By.cssSelector("a[href*='about_privacy']"));
      String s = elm.getText();
      System.out.println("Text is: " + s);
      //browser close
      driver.quit();
   }
}

Output

raja
Published on 25-Jun-2021 13:25:13
Advertisements