Wednesday 10 August 2016

Selenium2: WebDriver: getCssValue: Get value of given css property

WebElment interface provides getCssValue  method, which return the value of a given CSS property.


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 style="color: blue; margin-left: 30px;">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>


Assume index.jsp is available at http://localhost:8080/application. Following application gets the css properties color, margin-left  of the element h1.
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 colorValue = element.getCssValue("color");
  String marginLeftValue = element.getCssValue("margin-left");

  System.out.println("h1 tag set to color " + colorValue);
  System.out.println("h1 tag set to margin-left " + marginLeftValue);
  driver.close();
 }
}


Output
h1 tag set to color rgba(0, 0, 255, 1)
h1 tag set to margin-left 30px


Observe the output, color value is returned as rgba strings. RGBA stands for red green blue alpha. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).



Previous                                                 Next                                                 Home

No comments:

Post a Comment