Bird
Raised Fist0
Selenium Javatesting~15 mins

Getting text and attributes in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify text and attribute values of elements on the sample page
Preconditions (2)
Step 1: Open the browser and navigate to http://example.com/sample
Step 2: Locate the heading element with id 'main-heading' and get its visible text
Step 3: Locate the button element with id 'submit-btn' and get its 'type' attribute
Step 4: Locate the link element with id 'help-link' and get its 'href' attribute
Step 5: Verify the heading text is exactly 'Welcome to Sample Page'
Step 6: Verify the button 'type' attribute is 'submit'
Step 7: Verify the link 'href' attribute is 'http://example.com/help'
✅ Expected Result: The heading text matches 'Welcome to Sample Page', the button's type attribute is 'submit', and the link's href attribute is 'http://example.com/help'
Automation Requirements - Selenium WebDriver with Java and TestNG
Assertions Needed:
Assert heading text equals 'Welcome to Sample Page'
Assert button 'type' attribute equals 'submit'
Assert link 'href' attribute equals 'http://example.com/help'
Best Practices:
Use explicit waits to ensure elements are present before accessing
Use By.id locator strategy for element identification
Use TestNG assertions for validation
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 GetTextAndAttributesTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeClass
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        driver.manage().window().maximize();
    }

    @Test
    public void testGetTextAndAttributes() {
        driver.get("http://example.com/sample");

        WebElement heading = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("main-heading")));
        String headingText = heading.getText();
        Assert.assertEquals(headingText, "Welcome to Sample Page", "Heading text does not match");

        WebElement submitButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit-btn")));
        String buttonType = submitButton.getAttribute("type");
        Assert.assertEquals(buttonType, "submit", "Button type attribute does not match");

        WebElement helpLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("help-link")));
        String hrefValue = helpLink.getAttribute("href");
        Assert.assertEquals(hrefValue, "http://example.com/help", "Link href attribute does not match");
    }

    @AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

The @BeforeClass method sets up the ChromeDriver and WebDriverWait to wait up to 10 seconds for elements.

The test method navigates to the sample page URL.

It waits explicitly for the heading element to be visible, then gets its text and asserts it matches the expected string.

Similarly, it waits for the submit button and gets its type attribute, asserting it equals 'submit'.

Then it waits for the help link, gets its href attribute, and asserts it matches the expected URL.

The @AfterClass method closes the browser to clean up.

This approach uses explicit waits to avoid timing issues, uses By.id locators for clarity and speed, and TestNG assertions for clear validation messages.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits
Using incorrect locator strategies like XPath with absolute paths
Not closing the browser after test execution
Asserting on getText() without trimming or checking for case sensitivity
Bonus Challenge

Now add data-driven testing with 3 different sets of expected heading text, button type, and link href values

Show Hint

Practice

(1/5)
1. Which Selenium WebDriver method is used to retrieve the visible text from a web element in Java?
easy
A. getValue()
B. getText()
C. getAttribute()
D. getContent()

Solution

  1. Step 1: Understand the purpose of getText()

    The getText() method returns the visible text inside a web element on the page.
  2. Step 2: Differentiate from getAttribute()

    getAttribute() retrieves attribute values like 'href' or 'class', not visible text.
  3. Final Answer:

    getText() -> Option B
  4. Quick Check:

    Visible text = getText() [OK]
Hint: Use getText() for visible text, getAttribute() for attributes [OK]
Common Mistakes:
  • Confusing getText() with getAttribute()
  • Using getValue() which is not a Selenium method
  • Trying to get text with getContent() which doesn't exist
2. Which of the following is the correct syntax to get the value of the 'href' attribute from a WebElement named link in Selenium Java?
easy
A. String url = link.getAttribute("href");
B. String url = link.getText("href");
C. String url = link.getValue("href");
D. String url = link.getHref();

Solution

  1. Step 1: Recall getAttribute() usage

    To get an attribute value, use getAttribute("attributeName") on the WebElement.
  2. Step 2: Check syntax correctness

    String url = link.getAttribute("href"); correctly calls getAttribute("href") and assigns it to a String variable.
  3. Final Answer:

    String url = link.getAttribute("href"); -> Option A
  4. Quick Check:

    Attribute value = getAttribute("name") [OK]
Hint: Use getAttribute("attr") syntax to get attribute values [OK]
Common Mistakes:
  • Using getText() to get attribute values
  • Calling non-existent methods like getHref()
  • Passing attribute name as parameter to getText()
3. Consider the following Selenium Java code snippet:
WebElement button = driver.findElement(By.id("submitBtn"));
String text = button.getText();
String type = button.getAttribute("type");
System.out.println(text + "," + type);
If the button's visible text is "Submit" and its type attribute is "button", what will be printed?
medium
A. button
B. button,Submit
C. Submit
D. Submit,button

Solution

  1. Step 1: Understand getText() output

    getText() returns the visible text "Submit" from the button element.
  2. Step 2: Understand getAttribute() output

    getAttribute("type") returns the attribute value "button".
  3. Step 3: Analyze print statement

    Prints text + "," + type, which is "Submit,button".
  4. Final Answer:

    Submit,button -> Option D
  5. Quick Check:

    Text + "," + Attribute = Submit,button [OK]
Hint: getText() shows visible text; getAttribute() shows attribute value [OK]
Common Mistakes:
  • Mixing order of printed values
  • Expecting getText() to return attribute value
  • Ignoring the comma in print output
4. You wrote this code to get the placeholder attribute of an input field:
WebElement input = driver.findElement(By.name("email"));
String placeholder = input.getText();
But placeholder is empty. What is the error and how to fix it?
medium
A. Use getAttribute("placeholder") instead of getText()
B. Use getText() but call it after clicking the input
C. Use getValue() instead of getText()
D. Use getText() with parameter "placeholder"

Solution

  1. Step 1: Identify why getText() returns empty

    getText() returns visible text inside element, but placeholder is an attribute, not visible text.
  2. Step 2: Correct method to get attribute value

    Use getAttribute("placeholder") to get the placeholder attribute's value.
  3. Final Answer:

    Use getAttribute("placeholder") instead of getText() -> Option A
  4. Quick Check:

    Attributes need getAttribute() [OK]
Hint: Use getAttribute() for attributes like placeholder [OK]
Common Mistakes:
  • Using getText() to get attribute values
  • Trying to pass attribute name to getText()
  • Using non-existent getValue() method
5. You want to verify that a link's visible text is "Home" and its href attribute contains "index.html". Which Selenium Java code snippet correctly asserts both conditions?
hard
A. assertEquals(link.getText(), "index.html"); assertTrue(link.getAttribute("href").contains("Home"));
B. assertEquals(link.getAttribute("text"), "Home"); assertTrue(link.getText().contains("index.html"));
C. assertEquals(link.getText(), "Home"); assertTrue(link.getAttribute("href").contains("index.html"));
D. assertTrue(link.getText().equals("Home")); assertEquals(link.getAttribute("href"), "index.html");

Solution

  1. Step 1: Verify visible text with getText()

    Use assertEquals(link.getText(), "Home") to check visible text exactly.
  2. Step 2: Verify href attribute contains substring

    Use assertTrue(link.getAttribute("href").contains("index.html")) to check href contains the expected part.
  3. Final Answer:

    assertEquals(link.getText(), "Home"); assertTrue(link.getAttribute("href").contains("index.html")); -> Option C
  4. Quick Check:

    Text = getText(), Attribute = getAttribute() [OK]
Hint: Assert visible text with getText(), attribute with getAttribute() [OK]
Common Mistakes:
  • Using getAttribute("text") which is invalid
  • Comparing href exactly instead of contains
  • Mixing up text and href in assertions
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