What is the difference between getText and getAttribute? Answer, inside, with some nuances explored.
getText
Given a WebElement
getText
returns the text inside that element.
e.g. for
<p id="para1" class="main">A paragraph of text</p>
The following Assertion using getText
passes.
Assertions.assertEquals("A paragraph of text",
driver.findElement(By.id("para1")).
getText());
getAttribute
Given a WebElement
getAttribute
returns the value of an attribute on the element, or null
if the attribute does not exist.
e.g. for
<p id="para1" class="main">A paragraph of text</p>
The following Assertions using getAttribute
pass.
Assertions.assertEquals("main",
driver.findElement(By.id("para1")).
getAttribute("class"));
Assertions.assertNull(
driver.findElement(By.id("para1")).
getAttribute("name"));
Nuances
I used to have an exercise on my course with the aim of recreating the ‘getTitle’ command using different mechanisms.
It was a fun exercise, you can try it for yourself. I’ll wait while you do it…
Spoilers
When I first created the exercise, it was pretty easy since you could just grab the title element and do a getText
on it.
But… in later versions of WebDriver, getText
stopped working on title and I dropped the exercise.
There are many ways that you can still complete the exercise e.g. by parsing the full page text, and of course executing JavaScript to get the innerHtml
of the WebElement
(but we would not have covered JavaScript execution at that point on the course).
And now…
I noticed, that I can use getAttribute("text")
to get the text from the title element.
WebElement title = driver.findElement(By.tagName("title"));
Assertions.assertEquals(
"Basic Web Page Title",
title.getAttribute("text"));
Experiment
I haven’t reinstated the exercise but I thought it would be interesting to compare getText() and getAttribute(“text”) on different tags_._
I found it interesting that:
- getText() on
- html returns the text for the page (minus tags)
- body, div, strong, ul (as per html)
- getAttribute(“text”) on
- title returns the title (getText does not)
- script returns the inline script details
- option returns the text, as does getText
- sometimes getAttribute(“text”) worked on some a tags, where getText did not
I don’t think I’ll rely on this nuance, as WebDriver may not always do this, but I thought it interesting enough to note.
And as a side note, you can see the type of investigation process I go through when I find an oddity or something I don’t understand - I write code to check and explore combinations that would take too much time to investigate by hand.
Full Source
The full source for this is in my Webdriver Java FAQs project:
Specifically:
I have a ’test’ showing the basic usage, and an ‘Experiment’ test which you can point at any web page to see the difference between text and attribute for all the tags on that page.
If you want to learn how to use Selenium WebDriver with Java then check out our online courses.