Sometime We need to get the attribute values to perform some operation. In this tutorial I show how to get tag attribute values using Selenium Webdriver.
In the below HTML code, You see input tag which has multiple attribute 'type', 'class', 'name', 'id', 'autocomplete', 'autocomplete', 'value' and 'title' and hash values for each attribute. To get the attribute value, We need to use below selenium webdriver syntax.
Syntax: webelement_select+tag.getAttribute(attributeName).We try to get the attribute value that doesn't exists for the tag, it will return null value.
<!DOCTYPE html>
<html>
<head>
<title>Get Attribute values</title>
</head>
<body>
<h1>Get Attribute values</h1>
<form name="domf1" method="post">
<div>
<label for="Email" class="class-name1 class-name2"> Enter your email</label>
<input type="email" class="class-name3 class-name1 class-name2 class-name4" name="btnK" id="gbqfba" autocomplete="off" value="" title="Search">
</div>
</form>
</body>
</html>
Implementation Selenium Webdriver Source code for Upper HTML Code 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 Getattributevalueshandler {
public static void main(String[] args) throws InterruptedException {
// create objects and variables instantiation
WebDriver driver = new FirefoxDriver();
// maximize the browser window
driver.manage().window().maximize();
// launch the firefox browser and open the application url
driver.get("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/Attribute.html");
//Set timeout
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// identify input tag by proper selector
WebElement inputtag = driver.findElement(By.id("gbqfba"));
// Print all attribute value under unput tag
System.out.println("The Atribute of type value =: " + inputtag.getAttribute("type"));
System.out.println("The Atribute of class value =: " + inputtag.getAttribute("class"));
System.out.println("The Atribute of name value =: " + inputtag.getAttribute("name"));
System.out.println("The Atribute of autocomplete value =: " + inputtag.getAttribute("autocomplete"));
System.out.println("The Atribute of title value =: " + inputtag.getAttribute("title"));
System.out.println("The Atribute of href value =: " + inputtag.getAttribute("href"));
// close browser
driver.close();
}
}
After running the above code the output should look something like below:
No comments:
Post a Comment