0
0
Selenium Javatesting~10 mins

findElement by linkText in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page, finds a link by its visible text using Selenium's findElement(By.linkText()) method, clicks the link, and verifies that the navigation was successful by checking the page title.

Test Code - JUnit
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class LinkTextTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void testFindElementByLinkText() {
        driver.get("https://example.com");
        WebElement link = driver.findElement(By.linkText("More information..."));
        link.click();
        String expectedTitle = "IANA — IANA-managed Reserved Domains";
        assertEquals(expectedTitle, driver.getTitle());
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigate to https://example.comBrowser displays the Example Domain homepage with a link labeled 'More information...'-PASS
3Find the link element by visible link text 'More information...'Link element is located on the pageVerify element is found without exceptionPASS
4Click the found link elementBrowser navigates to the linked page-PASS
5Check the page title matches 'IANA — IANA-managed Reserved Domains'Browser shows the IANA reserved domains pageAssert that actual title equals expected titlePASS
6Close the browser and end the testBrowser window is closed-PASS
Failure Scenario
Failing Condition: The link with text 'More information...' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
Which Selenium method is used to find a link by its visible text?
AfindElement(By.id())
BfindElement(By.linkText())
CfindElement(By.className())
DfindElement(By.cssSelector())
Key Result
Always use the exact visible text when using findElement(By.linkText()) to avoid NoSuchElementException and ensure reliable element location.