How to click a link whose href has a certain substring in Selenium java?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A webpage can contain one or more hypertexts referencing other websites with the help of hyperlinks. This is enabled using the HTML anchor tag which has an attribute named href which takes the string value of the hyperlink. In this article, we will be demonstrating how to find specific anchor tags and explore the webpages suggested by them based on certain substrings present in the hyperlink using Selenium and Java.

Note that before attempting to run these codes, you must either have created a Java project with build tools (Maven/Gradle) or created a simple Java project and downloaded the Selenium JAR files from the internet. Also, you must have the respective driver for your browser.

Steps to click a link based on the presence of a substring in href

The website we will use to find anchor tags has the following HTML:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span{
            color: red;
        }
        body {
            margin: 0;
            font-size: 18px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            min-height: 100vh;
            text-align: center;
        }

    </style>
</head>
<body>
    <h2>Various links</h2>
    <a href="https://www.geeksforgeeks.org/learn-data-structures-and-algorithms-dsa-tutorial/">First link</a>
    <a href="https://www.geeksforgeeks.org/introduction-to-matrix-or-grid-data-structure-and-algorithms-tutorial/">Second link</a>
    <a href="https://www.geeksforgeeks.org/types-of-arrays/">Third link</a>
    <a href="https://www.geeksforgeeks.org/search-insert-and-delete-in-an-unsorted-array/">Fourth link</a><br><br>
    <a href="https://github.com/globbertrot/links/">Source Code</a>
</body>
</html>


The java code to find and click the hyperlinks based on substring present inside the href attribute of anchor tags is as follows:

App.java

Java
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class App {
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        driver.get("https://globbertrot.github.io/links/");

        try {
            WebElement url = driver.findElement(By.xpath("//a[contains(@href, 'array')]"));
          // WebElement url = driver.findElements(By.cssSelector("a[href*='substring']"));
            url.click();
        } 
      	catch (NoSuchElementException e) {}

        driver.quit();
    }  
}

Explanation

  • We have created a WebDriver object to visit our website which contains multiple anchor tags.
  • We can find the specific element inside the entire webpage using findElement() method of the driver object.
  • There are two methods using which we can find the particular anchor tag containing "array" (our substring) inside it's href attribute. We can either use XPath (XMLPath) or CSS selector to find it.
  • Once it is found, then we can use the click() method of the element object.
  • In case, there are no anchor tags with such substrings, it will throw NoSuchElementException which we are catching.

However, the above code will only find one anchor tag (first tag which contains the substring) with such condition even if there are multiple such tags which fit the criteria. In order to find all such anchor tags, we have to use findElements() method which will return list of elements based on the given criteria.

App.java

Java
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class App {
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        driver.get("https://globbertrot.github.io/links/");

        try {
            List<WebElement> listOfURL = driver.findElements(By.xpath("//a[contains(@href, 'array')]"));
          // List<WebElement> listOfURL = driver.findElements(By.cssSelector("a[href*='array']"));

            for (WebElement url: listOfURL) {
                url.click();
                driver.navigate().back();
            }

        } catch (NoSuchElementException e) {}

        driver.quit();
    }  
}

Explanation

  • We have created a driver object and visited our website which contains the links.
  • This time we have used findElements() method of driver object which takes the element identifier as argument same as before.
  • The above method returns the list of elements matching our criteria meaning it will contain all the anchor tags present in our webpage which has the particular substring in their href attribute.
  • Then we will iterate through this list and call the click() method individually for all elelents present inside the list.
  • We must also navigate to the previous page where all links were present, otherwise it will throw Stale Element Reference Exception.
  • Also, in case there are no images present on the website, we are catching the NoSuchElementException which is thrown if the driver is unable to find elements matching our criteria.

Output

Conclusion

In conclusion, clicking a link whose href contains a specific substring in Selenium Java is a straightforward process that enhances your web automation capabilities. By using methods like findElement() and findElements(), along with XPath or CSS selectors, you can easily locate and interact with the desired hyperlinks. This technique not only simplifies navigation through web pages but also empowers you to execute more complex automation scenarios efficiently. Mastering these skills will undoubtedly improve your proficiency in Selenium and elevate your automation projects to new heights.


Next Article
Article Tags :

Similar Reads