To fetch the tooltip or text written on any webpage there are differences in the use of getText() and getAttribute() method. In this post I have explained with an example where to use getText() and getAttribute()
getText() will work only for those tags which has starting and ending tag
for example, you have span :-
<Span class="ankur"> sample text </span>
if you write
finddelement(By.xpath("//span[@class='ankur']")).getText();
Output :-sample text
but if you have span like this i.e without ending tags
<Span class="ankur" value = "sample text">
and you write:-
finddelement(By.xpath("//span[@class='ankur']")).getText();
in this case it will not work, as getText method works only with those tags which has starting and ending tag in it and starting and ending tags mostly found in hyperlinks and static elements on the page.
So here we should use getAttribute method like this :-
finddelement(By.xpath("//span[@class='ankur']")).getAttribute("value");
Output:- sample text
Now moving to getAttribute("") method if you want to fetch the value from the text entered in the text field. Again here getText() will not work here you have to use getAttribute("value") with "value" as a parameter in it. As if whatever we write in text field it get saved in the value attribute of the element.
getText() will work only for those tags which has starting and ending tag
for example, you have span :-
<Span class="ankur"> sample text </span>
if you write
finddelement(By.xpath("//span[@class='ankur']")).getText();
Output :-sample text
but if you have span like this i.e without ending tags
<Span class="ankur" value = "sample text">
and you write:-
finddelement(By.xpath("//span[@class='ankur']")).getText();
in this case it will not work, as getText method works only with those tags which has starting and ending tag in it and starting and ending tags mostly found in hyperlinks and static elements on the page.
So here we should use getAttribute method like this :-
finddelement(By.xpath("//span[@class='ankur']")).getAttribute("value");
Output:- sample text
No comments:
Post a Comment