Selenium get attribute to get value of attribute

Selenium getAttribute() method

You can get value of attribute using getAttribute() method in selenium. As you know, all the web elements have one to many attributes. Sometimes you need to get it's value in selenium test to use it somewhere. At that time, selenium's build in getAttribute method will help to get value of that specific attribute.
Selenium getAttribute() method
  • getAttribute() method is part of WebElement interface which extends SearchContext and TakesScreenshot interfaces.
  • getAttribute() method is used to get value of that specific attribute of an element.
  • It will return value of attribute if attribute found.
  • It will return empty string if attribute not found.
  • Syntax for getAttribute() method : driver.findElement(By.Element_locator).getAttribute(Attribute_name);
In order to get value of element's attribute, First of all you need to locate that element. Then you can provide name of attribute inside getAttribute method to get it's value. Let us see it with practical example.

getAttribute() method example

Selenium getattribute() method

In above given image, element Grand Parent1 have total 3 attributes id, name and type. We will locate that element by id and then try to get it's name and type attribute's values.

package testPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class ClearExample {

	public static void main(String[] args) {
		System.setProperty("", "D:\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		//Find and locate textbox element by id.
		WebElement gp = driver.findElement("gparent_1"));
		//Get value of name attribute and print it in console.
		String name_Attr = gp.getAttribute("name");
		System.out.println("Name attribute value = "+name_Attr);
		//Get value of type attribute and print it in console.
		String type_Attr = gp.getAttribute("type");
		System.out.println("Type attribute value = "+type_Attr);
		//Get value of class attribute and print it in console.
		String class_Attr = gp.getAttribute("class");		
		System.out.println("class attribute value = "+class_Attr);	

In above given example, We located element by id. Then get attribute values of name, type, class and then print it in console. It will return values of name and type attributes. Value of class attribute will be null because that attribute is not available on element.

No comments:

Post a Comment