Posted on Leave a comment

How to Get Attribute of Element from Selenium?

In Selenium webdriver, we can use the getAttribute() method to get the value of an attribute. The attribute and its value appear as a key-value pair in HTML code.

Disabled, alt, id, href, style, title, and src are among the most well-known html properties. The value of the attribute we wish to get is supplied to the method as an argument.

Let’s have a look at how to collect attributes for an input field. The HTML for the input tag is shown below.

<input name="textField" class="textClass" type="text" aria-label="Input field" placeholder="Enter your name" id="name" label='Enter your name' />

With the code below, we can get the name, class and ID of the input Field.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class GetAttributes {

    public WebDriver driver;
    private By byInputField = By.name("textField");
                            
    @BeforeClass
    public void setUp() {
        driver = new FirefoxDriver();
        driver.get("https://testup.io");
    }

    @Test
    public void getAttribute_TextFieldName() {
        WebElement inputTextField = driver.findElement(byInputField);
        System.out.println("Name of the input field is:- " +inputTextField.getAttribute("name"));
    }

    @Test
    public void getAttribute_Id() {
        WebElement inputTextField = driver.findElement(byInputField);
        System.out.println("Id of the input field is:- "+ inputTextField.getAttribute("id"));
    }

    @Test
    public void getAttribute_class() {

        WebElement inputTextField = driver.findElement(byInputField);
        System.out.println("Class of the Input Field is:- "+ inputTextField.getAttribute("class"));

    }

    @Test
    public void getAttribute_InvalidAttribute() {

        WebElement inputTextField = driver.findElement(byInputField);
        //Will return null value as the 'status' attribute doesn't exists
        System.out.println("Invalid Attribute status of the input field is:- "+ inputTextField.getAttribute("status"));
    }
    
    @Test
    public void getAttribute_TextFieldLabel() {

        WebElement inputTextField = driver.findElement(byInputField);
        System.out.println("Label of the input field is:- "+ inputTextField.getAttribute("aria-label"));
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }
}

Output

Label of the button is: Enter your name
Name of the button is: textField
Id of the button is: name
Invalid Attribute status of the button is: null
Class of the button is: textClass
PASSED: getAttribute_inputTextFieldLabel
PASSED: getAttribute_inputTextFiedlName
PASSED: getAttribute_Id
PASSED: getAttribute_InvalidAttribute
PASSED: getAttribute_class