Friday 22 July 2016

Selenium2: WebDriver: getAttribute: Get the value associated with an attribute

WebElement interface provides getAttribute method, which takes an attribute name as argument and return the value associated with given attribute for an element. Following is the signature of getAttribute method.

String getAttribute(String name);
Return the attribute/property's current value or null if the value is not set.

For Example, in the following statement id and class are the attribute names and header1, headers are the values associated with the attributes.

<h1 id="header1" class="headers">Simple application to demonstrate Selenium webdriver</h1>


index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
 <div class="center">
  <h1 id="header1" class="headers">Simple application to demonstrate Selenium webdriver</h1>
 </div>

 <div class="center">
  <p id="para1">WebDriver interface provides number of methods to locate
   elements in a web page. You can locate an element by using class
   name, id, name, linktext etc.,</p>
 </div>
</body>
</html>


Suppose index.jsp is available at url “http://localhost:8080/application”. Following application extract the values associated with attributes id, class in h1 tag.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://localhost:8080/application");

  WebElement element = driver.findElement(By.tagName("h1"));

  String elemId = element.getAttribute("id");
  String elemValue = element.getAttribute("class");

  System.out.println("Value of the attribute id for h1 tag is " + elemId);
  System.out.println("Value of the attribute class for h1 tag is "
    + elemValue);
  driver.close();
 }
}


Output
Value of the attribute id for h1 tag is header1
Value of the attribute class for h1 tag is headers



Previous                                                 Next                                                 Home

No comments:

Post a Comment