What is the difference between getText() and getAttribute() in Selenium WebDriver?
<input attr1='a' attr2='b' attr3='c'>foo</input>
getAttribute(attr1)
you get 'a'
getAttribute(attr2)
you get 'b'
getAttribute(attr3)
you get 'c'
getText()
with no parameter you can only get 'foo'
getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like
<input name="Name Locator" value="selenium">Hello</input>
Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".
Returns:
The attribute's current value or null if the value is not set.
driver.findElement(By.name("Name Locator")).getAttribute("value") //
The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.
getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
driver.findElement(By.name("Name Locator")).getText();
'Hello' will appear
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
In above html tag we have different attributes like src
, alt
, width
and height
.
If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute()
method
Syntax:
getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104