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.
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.