Bird
Raised Fist0
Selenium Javatesting~15 mins

Getting text and attributes in Selenium Java - Deep Dive

Choose your learning style10 modes available
Overview - Getting text and attributes
What is it?
Getting text and attributes means extracting visible words or hidden details from elements on a web page during automated testing. Text is what a user sees inside an element, like a button label or paragraph. Attributes are extra information stored in the element's code, like links, IDs, or styles. Selenium lets you grab both to check if the page works as expected.
Why it matters
Without getting text and attributes, testers can't verify if the web page shows the right content or behaves correctly. Imagine checking a button without knowing its label or link; you might miss broken features. This ability helps catch errors early, improving user experience and saving time and money.
Where it fits
Before this, you should know how to locate elements on a page using Selenium locators. After learning this, you can move on to interacting with elements, like clicking or typing, and then validating page states or automating complex user flows.
Mental Model
Core Idea
Getting text and attributes is like reading the visible label and hidden notes on a web page element to understand what it shows and how it behaves.
Think of it like...
It's like picking up a product in a store: the text is the label you read on the box, and the attributes are the hidden details like the barcode or ingredients list that tell you more about the product.
┌───────────────┐
│ Web Element   │
│ ┌───────────┐ │
│ │ Text      │ │  <-- Visible words users see
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Attributes│ │  <-- Hidden info like href, id, class
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationLocating elements on a page
🤔
Concept: Before getting text or attributes, you must find the element you want to inspect.
In Selenium Java, you use methods like driver.findElement(By.id("example")) to find elements. This returns a WebElement object representing that part of the page.
Result
You get a WebElement that points to the exact element on the page.
Knowing how to locate elements is the first step because you can't get text or attributes without first finding the element.
2
FoundationUnderstanding text vs attributes
🤔
Concept: Text is the visible content inside an element; attributes are extra properties in the element's HTML tag.
For example, Click here has text 'Click here' and an attribute href='link.html'. Text is what users read; attributes control behavior or style.
Result
You can distinguish between what users see and what controls the element behind the scenes.
Separating text and attributes helps you know what to check depending on the test goal: visible content or element properties.
3
IntermediateUsing getText() to retrieve visible text
🤔Before reading on: do you think getText() returns hidden text inside elements or only visible text? Commit to your answer.
Concept: getText() extracts only the visible text inside an element, ignoring hidden or script content.
Example: WebElement button = driver.findElement(By.id("submit")); String label = button.getText(); System.out.println(label); // prints the button's visible label
Result
You get the exact words users see on the page inside that element.
Understanding getText() returns only visible text prevents confusion when hidden text or attributes don't show up in your tests.
4
IntermediateUsing getAttribute() to access element properties
🤔Before reading on: do you think getAttribute() can retrieve any attribute, even if it is not visible on the page? Commit to your answer.
Concept: getAttribute() fetches the value of any attribute from the element's HTML tag, visible or hidden.
Example: WebElement link = driver.findElement(By.cssSelector("a.home")); String hrefValue = link.getAttribute("href"); System.out.println(hrefValue); // prints the URL the link points to
Result
You get the exact attribute value, like URLs, IDs, or classes, regardless of visibility.
Knowing getAttribute() accesses hidden data helps you verify element behavior beyond what users see.
5
IntermediateCommon attributes to check in tests
🤔
Concept: Certain attributes like href, src, class, id, value, and style are often checked to confirm correct page behavior.
For example, checking href ensures links go to the right place; checking value confirms input fields hold expected data. Example: String inputValue = driver.findElement(By.name("email")).getAttribute("value");
Result
You can validate that elements have correct properties, not just visible text.
Focusing on key attributes lets you write meaningful tests that catch subtle bugs.
6
AdvancedHandling dynamic text and attributes
🤔Before reading on: do you think getText() and getAttribute() automatically update if the page changes after loading? Commit to your answer.
Concept: Text and attributes can change dynamically; you must re-fetch elements or their properties after page updates.
If JavaScript changes a button label or attribute after page load, calling getText() or getAttribute() on the old WebElement may give stale data or errors. You should locate the element again or wait for updates. Example: WebElement button = driver.findElement(By.id("dynamicBtn")); // After some action that changes text String newText = button.getText(); // May throw StaleElementReferenceException // Correct approach: re-find element button = driver.findElement(By.id("dynamicBtn")); newText = button.getText();
Result
You get fresh, accurate text or attribute values reflecting the current page state.
Understanding element staleness prevents flaky tests and ensures you verify the latest page content.
7
ExpertDifferences between getText() and attribute 'textContent'
🤔Before reading on: do you think getText() and getAttribute("textContent") always return the same text? Commit to your answer.
Concept: getText() returns visible text after rendering and CSS effects; getAttribute("textContent") returns raw text inside the element, including hidden parts.
Example: WebElement elem = driver.findElement(By.id("example")); String visibleText = elem.getText(); String rawText = elem.getAttribute("textContent"); System.out.println("Visible: " + visibleText); System.out.println("Raw: " + rawText); Visible text excludes hidden or script text; raw text includes all text nodes inside the element.
Result
You can choose the right method depending on whether you want user-visible text or all text content.
Knowing this subtle difference helps avoid confusion when tests fail due to hidden text or formatting.
Under the Hood
Selenium communicates with the browser through WebDriver protocols. When getText() is called, the browser renders the page and returns only the visible text nodes inside the element, excluding hidden or script content. getAttribute() fetches the attribute value directly from the element's HTML tag in the DOM, regardless of visibility or rendering. This separation ensures tests can verify both what users see and the underlying element properties.
Why designed this way?
Separating visible text from attributes reflects how browsers render pages: users see only visible text, but attributes control behavior and styling. This design allows testers to check both user experience and technical correctness. Alternatives like returning raw HTML or all text would confuse tests by mixing visible and hidden data.
┌───────────────┐
│ Selenium Test │
└──────┬────────┘
       │ calls getText() or getAttribute()
       ▼
┌─────────────────────┐
│ Browser WebDriver    │
│ ┌───────────────┐   │
│ │ Render Engine  │◄──┤ getText() returns visible text
│ └───────────────┘   │
│ ┌───────────────┐   │
│ │ DOM Inspector │◄──┤ getAttribute() returns attribute value
│ └───────────────┘   │
└─────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does getText() return hidden text inside elements? Commit to yes or no.
Common Belief:getText() returns all text inside an element, including hidden parts.
Tap to reveal reality
Reality:getText() returns only visible text after rendering; hidden text is excluded.
Why it matters:Tests expecting hidden text with getText() will fail or miss bugs, causing false negatives.
Quick: Can getAttribute() retrieve CSS styles applied to an element? Commit to yes or no.
Common Belief:getAttribute() can get CSS styles like color or font-size directly.
Tap to reveal reality
Reality:getAttribute() only retrieves HTML attributes, not computed CSS styles. Styles must be fetched differently.
Why it matters:Relying on getAttribute() for styles leads to incorrect test results about element appearance.
Quick: If the page changes text dynamically, will getText() automatically update without re-finding the element? Commit to yes or no.
Common Belief:Once you have a WebElement, getText() always returns the current text even if the page changes.
Tap to reveal reality
Reality:WebElement references can become stale after page updates; you must locate elements again to get fresh text.
Why it matters:Ignoring this causes flaky tests with stale element errors or outdated data.
Quick: Does getAttribute("textContent") behave the same as getText()? Commit to yes or no.
Common Belief:getAttribute("textContent") and getText() return the same visible text.
Tap to reveal reality
Reality:getAttribute("textContent") returns all text inside the element, including hidden or script text, unlike getText().
Why it matters:Confusing these leads to tests that fail unexpectedly due to hidden text presence.
Expert Zone
1
getText() depends on browser rendering and CSS; invisible elements or those hidden by styles return empty strings.
2
getAttribute() can return null if the attribute does not exist, so tests must handle null safely.
3
Some attributes like 'value' behave differently across element types; for example, input fields store user input in 'value', but others may not.
When NOT to use
Avoid using getText() when you need raw or hidden text; use getAttribute("textContent") instead. Don't rely on getAttribute() for computed styles; use JavaScript execution or WebDriver's getCssValue() method. For dynamic pages, avoid caching WebElements; always re-locate elements after page changes.
Production Patterns
In real-world tests, getText() is used to verify labels, messages, and visible content. getAttribute() checks links, IDs, classes, and input values. Tests often combine both to validate UI and underlying data. Handling dynamic content involves explicit waits and re-fetching elements to avoid stale references.
Connections
DOM (Document Object Model)
builds-on
Understanding how the DOM represents elements and their attributes helps grasp why getAttribute() accesses raw HTML properties while getText() reflects rendered content.
CSS Styling and Visibility
related concept
Knowing how CSS controls element visibility explains why getText() excludes hidden text, linking style rules to test outcomes.
Human Perception in UI Design
cross-domain analogy
Just like humans only notice visible labels and ignore hidden tags on products, tests using getText() focus on user-visible content, highlighting the importance of user perspective in testing.
Common Pitfalls
#1Trying to get text from a hidden element expecting visible content.
Wrong approach:String text = driver.findElement(By.id("hiddenElement")).getText(); // returns empty string
Correct approach:Use getAttribute("textContent") if you need hidden text: String text = driver.findElement(By.id("hiddenElement")).getAttribute("textContent");
Root cause:Misunderstanding that getText() only returns visible text, so hidden elements appear empty.
#2Using getAttribute() to get CSS styles directly.
Wrong approach:String color = driver.findElement(By.id("button")).getAttribute("color"); // returns null
Correct approach:Use getCssValue(): String color = driver.findElement(By.id("button")).getCssValue("color");
Root cause:Confusing HTML attributes with CSS properties; getAttribute() does not access computed styles.
#3Not re-finding elements after page updates causing stale element errors.
Wrong approach:WebElement elem = driver.findElement(By.id("dynamic")); // page changes String text = elem.getText(); // throws StaleElementReferenceException
Correct approach:Re-locate element after update: elem = driver.findElement(By.id("dynamic")); String text = elem.getText();
Root cause:Assuming WebElement references remain valid after DOM changes.
Key Takeaways
Getting text and attributes lets you verify both what users see and the hidden properties controlling web elements.
getText() returns only visible text after rendering, while getAttribute() fetches raw HTML attribute values regardless of visibility.
Dynamic pages require re-finding elements to avoid stale references and get fresh text or attribute values.
Understanding the difference between visible text and raw content prevents common test failures and flaky results.
Using the right method for your test goal ensures accurate validation of web page behavior and appearance.

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