How to click a link whose href has a certain substring in Selenium java?
Last Updated :
03 Oct, 2024
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.
Similar Reads
How to get an attribute value from a href link in Selenium java? When working with Selenium WebDriver in Java, automating web interactions often involves handling hyperlinks. A common task is to extract the attribute value from a <a> tag, specifically the href attribute, which contains the link's destination URL. Extracting this href value allows you to ver
3 min read
How to click on an image using Selenium in Java? Selenium, a popular tool for automating web application testing across browsers, often requires image interaction. In this article we will discuss how to clicking on image using Selenium in Java.PrerequisitesJava Development Kit (JDK) installed.Selenium WebDriver library added to your project.A supp
3 min read
How to Click on a Hyperlink Using Java Selenium WebDriver? An open-source tool that is used to automate the browser is known as Selenium. Automation reduces human effort and makes the work comparatively easier. There are numerous circumstances in which the user wants to open a new page or perform a certain action with the click of the hyperlink. In this art
4 min read
How to change focus to a new popup tab in Selenium java? Selenium WebDriver is a popular tool for automating web applications and performing UI testing. One of the challenges while testing is handling popup windows or new browser tabs that open when users interact with web elements like buttons or links. These popups may contain login forms, confirmation
2 min read
How to Get All Available Links on the Page using Selenium in Java? Selenium is an open-source Web-Automation tool that is used to automate web Browser Testing. The major advantage of using selenium is, that it supports all major web browsers and works on all major Operating Systems, and it supports writing scripts on various languages such as Java, Â JavaScript, C#
2 min read
How to find the src of an image in Selenium java? Selenium WebDriver is a popular automation tool used for testing web applications across different browsers. One common task in web automation is extracting information from web elements, such as retrieving the src attribute of an image. The src attribute holds the URL of the image, and Selenium pro
4 min read