findElement by linkText in Selenium Java - Build an Automation Script
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; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class AboutUsLinkTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver executable if needed // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test public void testAboutUsLinkNavigation() { driver.get("https://example.com"); // Locate the link by exact visible text 'About Us' WebElement aboutUsLink = wait.until( ExpectedConditions.elementToBeClickable(By.linkText("About Us")) ); aboutUsLink.click(); // Wait until URL contains '/about' wait.until(ExpectedConditions.urlContains("/about")); // Assert the URL is exactly 'https://example.com/about' String currentUrl = driver.getCurrentUrl(); Assert.assertEquals(currentUrl, "https://example.com/about", "URL after clicking About Us link should be correct"); // Assert the page title contains 'About Us' String title = driver.getTitle(); Assert.assertTrue(title.contains("About Us"), "Page title should contain 'About Us'"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test class uses Selenium WebDriver with Java and TestNG for assertions.
setUp(): Initializes ChromeDriver and WebDriverWait with a 10-second timeout. Maximizes the browser window for better visibility.
testAboutUsLinkNavigation(): Opens the homepage URL. Uses By.linkText("About Us") to find the link with exact visible text 'About Us'. Waits until the link is clickable, then clicks it.
After clicking, it waits until the URL contains '/about' to ensure the page has loaded. Then it asserts the URL is exactly 'https://example.com/about' and the page title contains 'About Us'.
tearDown(): Closes the browser after the test to free resources.
This structure follows best practices: explicit waits avoid timing issues, assertions verify expected outcomes, and the test is cleanly organized.
Now add data-driven testing to verify navigation for three different links: 'About Us', 'Contact', and 'Services'.