Next-Gen App & Browser
Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles
To click on a hyperlink using Selenium WebDriver in Java, you can locate the anchor (<a>)
tag using its visible link text, partial link text, or other locators like XPath or CSS Selector. Once located, you can use the click()
method provided by the WebElement interface to simulate the user click action.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ClickHyperlinkExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// Navigate to the desired web page
driver.get("https://www.lambdatest.com");
// Locate the hyperlink by its visible text
WebElement link = driver.findElement(By.linkText("Click here"));
// Perform click operation on the hyperlink
link.click();
// Wait until the new page is loaded
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.urlContains("new-page"));
// Close the browser
driver.quit();
}
}
If the link text is dynamic or not unique, you can use other strategies:
By using Selenium WebDriver this way, you can simulate real user behavior and automate link-click actions effectively in your test scripts.
For a deeper understanding of How to click on a hyperlink using Selenium WebDriver, explore this detailed guide on Selenium WebDriver.
KaneAI - Testing Assistant
World’s first AI-Native E2E testing agent.