Testing a web page can be a gargantuan task considering all the elements and variables that come together to make a page work. Selenium automation is a great way to overcome these challenges and automate everything you would manually do. For example, Selenium makes it so much easier to take a screenshot using Python instead of doing it manually every time you come across a website issue.
Similarly, there are multiple scenarios while writing automation test cases when we need to verify a specific attribute on the web page. To ease our execution, the method to getAttribute() in Selenium comes to the rescue. In this blog, we will understand what an attribute is and how we can handle web elements’ attributes using the Selenium getAttribute() method.
Let’s get to it, shall we?
What Is An Attribute?
An attribute in HTML defines the properties of the element. Attributes are made up of name-value pairs, i.e., an attribute has a name and the corresponding value of the same. They are specified in the opening tag, and their values are enclosed in double-quotes. Some of the examples of HTML attributes are:
- < a target=”_blank” href=”//www.phptravels.net” class=”btn btn-primary btn-lg btn-block” >
- < img src=”https://phptravels.com/assets/img/front.png” class=”well-sm icon-resources img100” alt=”homepage” >
- < input style="height:40px; width:300px;" class="form-control newsletter_email" type="text" placeholder="your@email.com" name="email" id="address" >
- < button onclick="if (!window.__cfRLUnblockHandlers) return false; subscribe_click()" class="btn btn-primary" value="" >SUBSCRIBE< /button >
As you can see above, the HTML tags have different attributes and corresponding values, like, the input tag has multiple attributes like style, class, type, placeholder, name, and id. Corresponding to each attribute, there is a value in double-quotes, viz, height:40px; width:300px; form-control newsletter_email; text; your@email.com; email and address respectively.
Now that you know all about an attribute for an HTML web element and what it looks like let us see how we can fetch the attribute values with the help of getAttribute() in Selenium WebDriver.
Check out- Using Thread.sleep() in Java with Selenium
Using getAttribute() In Selenium: What, Why & How?
In this section, we will dive deeper into Selenium getAttribute() method. We will be covering everything from what the getAttribute() method is to using getAttribute() in Selenium. We will be using Selenium WebDriver in our instances below.
What Is getAttribute()?
getAttribute() is a method of IWebElement Interface. The IWebElement interface helps in performing all the interactions or operations on the web page elements. The getAttribute() method helps to get the value of any attribute of a web element, which is returned as a String.
If an attribute has a Boolean value, the method returns either True or null. Also, if there is no attribute, the method will return null. We will see all the different attributes and the values that they return in a while, but let us see why we need to use the getAttribute() method before jumping to that part.
Why Use getAttribute()?
Consider a scenario where you need to verify the placeholder text on an input field or maybe the image source or even the field’s dimensions. This is where the getAttribute() method comes to the rescue. You just have to find the web element that contains the attribute and use the getAttribute() method to find its value. Below is a simple line of code that you will have to write-
String value = driver.findElement(by.id(“Web element id”)).getAttribute(“Attribute name”);
In the next section, we will see a working example of fetching the attribute values using the getAttribute() method.
How To Use Selenium getAttribute()?
Now that we have seen the basic syntax of using the getAttribute() method, we will see a working example of fetching values using getAttribute(). We will use a dummy website to write a basic test script. Without further ado, let us quickly see the use case and then proceed with the code.
Use Case-
- Navigate to the dummy website.
- Get the image source value of the image in the Homepage Front-End and print the same.
- Verify the placeholder value of the Join Newsletter text field.
Let us now see how the code for the above use case would look like-
package attribute;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AttributeTest {
WebDriver driver;
//Method to set up the browser and open the dummy website
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://phptravels.com/demo/");
driver.manage().window().maximize();
}
//Test method to get the different attribute values
@Test
public void getAttrVals() {
//Fetching the image source
WebElement image = driver.findElement(By.xpath("//img[@class=\"well-sm icon-resources img100\"]"));
System.out.println("The image source is : "+image.getAttribute("src"));
//Fetching the placeholder value
WebElement emailField = driver.findElement(By.id("address"));
String placeholderVal = emailField.getAttribute("placeholder");
String expectedVal = "your@email.com";
if(placeholderVal.equalsIgnoreCase(expectedVal))
System.out.println("The placeholder value is expected, ie : "+placeholderVal);
else
System.out.println("The placeholder value is not correct --- " +placeholderVal);
//Getting attribute value of an attribute that is not present on the page
WebElement logInBtn = driver.findElement(By.xpath("//*[@class=\"btn yx-nfn yx-njg\"]"));
System.out.println("The value of an attribute that doesn't exist is : " +logInBtn.getAttribute("type"));
}
//Method to close the webdriver session
@AfterTest
public void burnDown() {
driver.quit();
}
}
Code Walkthrough
Let us now do a quick walkthrough of the above code:
- The setUp() method sets up the browser instance and opens the URL of the dummy website.
- Next, the Test method, viz, getAttrVals() has the code to fetch the attribute values.
- We first locate the image using the XPath and then print the value of the ‘src’ attribute using the WebElement interface method: image.getAttribute(“src”).
- Then we locate the emailField text box and save the String value in a variable using emailField.getAttribute(“placeholder”).
- Next, we use the if-else conditional statements to verify if the fetched value equals the expected value and correspondingly print the console window’s result.
- We then locate the login button on the web page and try to find the value of an attribute that does not exist by using the code- logInBtn.getAttribute(“type”). Note that the attribute name “type” is not present in the tag for the web element.
- After performing the test steps, we jump on to the burnDown() method to close the WebDriver instance.
Output
On executing the above code you will see the result in the console output like below:
As is clearly visible from the test results, the src value for the image is printed on the console window. Next, the placeholder value matches the expected value, and the corresponding success result is printed on the console window. Finally, the value for the attribute that is not present is displayed as blank or null because no attribute name as specified in the test script for the Log In button is present.
Did you see how easy it was to implement the getAttribute() in the Selenium test script? You can use this method as per your requirements to validate a certain functionality of our web application.
Let us now quickly see important points that differentiate getText() , getAttribute(), and getCssValue() methods.
getText() vs getAttribute() vs getCssValue()
While going out on interviews, one of the most frequently asked questions on Selenium automation is stating the differences between various Selenium methods, viz, getText(), getAttribute(), and getCssValue().
getText() is used to get the visible inner text of a web element and the sub elements. By visible, we mean that the text which is not hidden by CSS. You can refer to more about the getText() method from our article on how to get text of an element in Selenium.
getAttribute(String attributeName), as discussed above, is used to fetch the attribute value of an HTML tag of the web element. There are multiple attributes like style, src, placeholder, href, etc. which are passed as a string parameter to the method. The value corresponding to the parameter is returned.
getCssValue(), similar to the attribute values in getAttribute(), you can find the CSS properties of the web elements using the getCssValue() method. You can go through the documentation for the getCssValue() method for your understanding, and we will cover it in a post later.
Implementing Selenium getAttribute() In LambdaTest Grid Cloud
We now know how we can use the Selenium getAttribute() method to fetch web element properties. Next, we will see how we can leverage LambdaTest’s Selenium Grid cloud to run tests in parallel and get the test results by a single execution.
Use Case
- Navigate to the LambdaTest website.
- Locate the email address text box and fetch the placeholder value.
We will execute this case on the LambdaTest grid to see how the execution results are generated. Subsequently, you can run tests across parallel browsers by referring to our article on using Selenium Grid for automated browser testing for further understanding.
The code for the same would look like below-
package attribue;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ParallelAttributeTest {
public String username = "YOUR_USERNAME";
public String accesskey = "YOUR_ACCESS_KEY";
public static RemoteWebDriver driver = null;
public String gridURL = "@hub.lambdatest.com/wd/hub";
boolean status = false;
//Method to set up the browser and open the lambda test website
@BeforeClass
public void setUp() {
//You need to set desired capabilities which you can generate from Capability Generator from Lambda Test as per your requirements
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "chrome");
capabilities.setCapability("version", "81.0");
capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will get any available one
capabilities.setCapability("build", "LambdaTestProject");
capabilities.setCapability("name", "LambdaTestGetAttributeValueProject");
capabilities.setCapability("network", true); // Enables network logs
capabilities.setCapability("visual", true); // Enables step by step screenshot
capabilities.setCapability("video", true); // Enables video recording
capabilities.setCapability("console", true); // Captures console logs
try {
driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
} catch (MalformedURLException e) {
System.out.println("Invalid grid URL");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//Test method to get the attribute value
@Test
public void getAttrVals() {
driver.get("https://www.lambdatest.com/");
driver.manage().window().maximize();
System.out.println("The attribute value is : " +driver.findElement(By.id("useremail")).getAttribute("placeholder"));
}
//Method to close the webdriver session
@AfterClass
public void burnDown() {
driver.quit();
}
}
You will see the execution results under the Automation tab of your LambdaTest dashboard on running the above test.
You can also see the placeholder value is printed in the Eclipse console window, indicating that our getAttribute() method fetched the correct results.
Now you can smoothly run your Selenium automation tests on the LambdaTest Grid for enhanced parallel execution along with extensive support for report generation.
Conclusion
To sum up – in this blog:
- We understood what an HTML attribute is and why it is placed in the opening tags.
- We saw the know-how about the getAttribute() method of Selenium WebDriver, with details on what it is, why we use it, and finally implemented it in a dummy application.
- We saw how efficiently we could use the getAttribute() method to verify the web elements’ different characteristics.
- We saw how getText() and getCssValue() are different from the getAttribute() method of Selenium WebDriver.
Finally, we implemented getAttribute() in the Selenium Grid cloud offered by LambdaTest. It is safe to say that getAttribute() is pivotal to Selenium test automation, especially when it comes to fetching and interacting with specific web elements. On the plus side, using a cloud-based Selenium Grid lets you do this for a combination of 2000+ browsers & operating systems. That’s easily the best way to use getAttribute()!
Happy testing!
Top comments (0)