Skip to main content

Jun 17, 2014 - 2 minute read - Selenium Simplified Blog WebDriver

Selenium WebDriver getAttribute nuance

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…


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.

You could still complete the exercise by parsing the full page text, and of course executing JavaScript to get the innerHtml of the element (but we would not have covered JavaScript execution at that point on the course).

And now…

I noticed, in 2.42.2, that I can use getAttribute(“text”) to get the text from the title element.

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.

Feel free to repeat the exercise on your pages if you want. The code I used is in my WebDriverExperiments project on github

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.

As you can see from the code, sometimes I write hacky code, because it is essentially throw away for my learning purpose, and I ignore the simple defects in it.





You will need a Github account to comment. Or you can contact me with your comment.

I reserve the right to delete spam comments e.g. if your comment adds no value and its purpose is simply to create a backlink to another site offering training, or courses, or etc.