Bird
Raised Fist0
Selenium Javatesting~15 mins

findElement by linkText in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify navigation to About Us page using link text
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com'
Step 2: Locate the link with the exact visible text 'About Us'
Step 3: Click on the 'About Us' link
Step 4: Wait for the About Us page to load
✅ Expected Result: The browser navigates to the About Us page with URL 'https://example.com/about' and page title contains 'About Us'
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify current URL is 'https://example.com/about'
Verify page title contains 'About Us'
Best Practices:
Use By.linkText locator to find the link
Use explicit waits to wait for page load or element visibility
Use assertions from a testing framework like TestNG or JUnit
Close the browser after test execution
Automated Solution
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.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.

Common Mistakes - 4 Pitfalls
Using By.partialLinkText instead of By.linkText
Not using explicit waits before clicking the link
Hardcoding URLs without waiting for page load
Not closing the browser after test
Bonus Challenge

Now add data-driven testing to verify navigation for three different links: 'About Us', 'Contact', and 'Services'.

Show Hint

Practice

(1/5)
1. What does driver.findElement(By.linkText("Home")) do in Selenium Java?
easy
A. Finds the first link on the page with visible text exactly "Home"
B. Finds all links containing the text "Home" anywhere
C. Finds a button with the label "Home"
D. Finds an element by its HTML id "Home"

Solution

  1. Step 1: Understand the method used

    findElement(By.linkText("Home")) searches for a link whose visible text exactly matches "Home".
  2. Step 2: Differentiate from other locators

    It does not find buttons or elements by id, nor does it find partial matches (that would be partialLinkText).
  3. Final Answer:

    Finds the first link on the page with visible text exactly "Home" -> Option A
  4. Quick Check:

    Exact link text = Finds link by text [OK]
Hint: Exact visible text matches linkText locator [OK]
Common Mistakes:
  • Confusing linkText with partialLinkText
  • Using linkText to find buttons or other elements
  • Expecting partial matches with linkText
2. Which of the following is the correct syntax to find a link with text "Contact Us" using Selenium Java?
easy
A. driver.findElement(By.linkText("Contact Us"));
B. driver.findElement(By.linkText(Contact Us));
C. driver.findElement(By.linkText['Contact Us']);
D. driver.findElement(By.linkText{ "Contact Us" });

Solution

  1. Step 1: Check correct method and parameter format

    The method findElement(By.linkText("Contact Us")) uses double quotes around the string and parentheses correctly.
  2. Step 2: Identify syntax errors in other options

    Options B, C, and D have missing quotes, wrong brackets, or braces which cause syntax errors.
  3. Final Answer:

    driver.findElement(By.linkText("Contact Us")); -> Option A
  4. Quick Check:

    Correct syntax uses parentheses and quotes [OK]
Hint: Use parentheses and quotes exactly as method requires [OK]
Common Mistakes:
  • Omitting quotes around link text
  • Using wrong brackets like [] or {}
  • Missing parentheses after method call
3. What will happen when this code runs?
WebElement link = driver.findElement(By.linkText("About"));
System.out.println(link.getText());

Assuming the page has a link with visible text exactly "About".
medium
A. It prints the href attribute of the link
B. It throws NoSuchElementException
C. It prints "About" to the console
D. It prints null

Solution

  1. Step 1: Locate the link by exact text

    The code finds the link with visible text "About" successfully because it exists on the page.
  2. Step 2: Print the visible text of the found element

    link.getText() returns the visible text of the link, which is "About".
  3. Final Answer:

    It prints "About" to the console -> Option C
  4. Quick Check:

    getText() returns visible text [OK]
Hint: getText() returns exact visible text of found element [OK]
Common Mistakes:
  • Expecting getText() to print href attribute
  • Assuming NoSuchElementException without checking page content
  • Thinking getText() returns null if element found
4. You wrote this code but it throws NoSuchElementException:
driver.findElement(By.linkText("Login"));

The page has a link with text "Log In" (with a space). What is the problem?
medium
A. You must use partialLinkText for any link with spaces
B. linkText cannot find links with spaces
C. The method findElement is deprecated for links
D. The linkText must match the text exactly, so "Login" does not match "Log In"

Solution

  1. Step 1: Understand exact matching requirement

    By.linkText requires the visible text to match exactly, including spaces.
  2. Step 2: Compare given text and actual link text

    "Login" (no space) does not match "Log In" (with space), so element is not found.
  3. Final Answer:

    The linkText must match the text exactly, so "Login" does not match "Log In" -> Option D
  4. Quick Check:

    Exact text match required for linkText [OK]
Hint: Check spaces and case exactly when using linkText [OK]
Common Mistakes:
  • Assuming partial matches work with linkText
  • Thinking spaces are ignored in linkText
  • Believing findElement is deprecated for links
5. You want to click a link with text "Terms & Conditions" but the page sometimes shows it as "Terms and Conditions". How can you write Selenium Java code to handle both cases?
hard
A. Use findElement(By.id("terms")) assuming id is always present
B. Use try-catch: try findElement(By.linkText("Terms & Conditions")), if fails try findElement(By.linkText("Terms and Conditions"))
C. Use findElement(By.partialLinkText("Terms &")) to match both
D. Use findElement(By.linkText("Terms")) to match both

Solution

  1. Step 1: Understand exact matching limitation

    linkText requires exact text, so you must try both versions separately.
  2. Step 2: Use try-catch to attempt both texts

    Try finding the link with "Terms & Conditions" first; if it throws exception, catch it and try "Terms and Conditions".
  3. Final Answer:

    Use try-catch: try findElement(By.linkText("Terms & Conditions")), if fails try findElement(By.linkText("Terms and Conditions")) -> Option B
  4. Quick Check:

    Try both exact texts with error handling [OK]
Hint: Try exact texts one by one with try-catch [OK]
Common Mistakes:
  • Using partialLinkText that may match wrong links
  • Assuming partial text "Terms" matches both safely
  • Assuming id locator is always available
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard