getAttribute() Method

How to perform an actions on webelement to perform such tasks like clicking the submit button, typing the texts in the text input area, click the dropdown list, check or uncheck the box, clicking the radio button, etc.,  All its comes under actions.  Hence, in selenium web driver we have lots of
methods to perform for the certain functions.

Attributes  and its Values plays the major role to drive automation for web browsers.  In the html web page source code we can see the attribute and attribute values.

For example, In facebook homepage, the user id and password input will be like this.

<input type="email" class="inputtext" name="email" id="email" value="" tabindex="1">
<input type="password" class="inputtext" name="pass" id="pass" tabindex="2">

The above example, the type, class, name, id, value and tabindex are Attribute's.  The attribute values are within the double quotes.  WebDriver will drive through with this help of WebElements.  These attributes value are String type. Below is the syntax to get the Attribute and its values.

JAVA API Syntax : java.lang.String getAttribute(java.lang.String name)

Below code will work to get Facebook home page attribute and its values for user id and password.


Input:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class gtattribute {
 
public static void main(String args[]) {

//Launching the firefoxbrowser
WebDriver driver = new FirefoxDriver();
  
//Implicit wait method is used to wait for the webelement to load  
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
  
//Navigate to FB page
driver.get("http://www.facebook.com");
  
//Finding the element using name attribute and assign it to variable
WebElement UserID = driver.findElement(By.name("email"));
  
//Printing the Attribute values in the console
System.out.println("Type Attributes and its values: "
+UserID.getAttribute("type"));

System.out.println("Class Attributes and its values: "
+UserID.getAttribute("class"));

System.out.println("Name Attributes and its values: "
+UserID.getAttribute("name"));

System.out.println("ID Attributes and its values: "
+UserID.getAttribute("id"));

System.out.println("Value Attributes and its values: "
+UserID.getAttribute("value"));
}
}
Output:
Type Attributes and its values: email
Class Attributes and its values: inputtext
Name Attributes and its values: email
ID Attributes and its values: email
Value Attributes and its values: 
Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →