Automation Using Selenium Webdriver
Showing posts with label Reading Font Properties In Selenium WebDriver Using .getCssValue() Method. Show all posts
Showing posts with label Reading Font Properties In Selenium WebDriver Using .getCssValue() Method. Show all posts

Monday 12 December 2016

Reading Font Properties In Selenium WebDriver Using .getCssValue() Method



Sometimes you need to read font properties like font size, font color, font family, font background color etc.. during WebDriver test case execution. Selenium WebDriver Is very wast API and It has many built In methods to perform very small small operations on web page.Reading font property manually Is very simple task using firebug as shown In bellow given Image




If you wants to read above shown font property In selenium webdriver then you can do It using .getCssValue() Method. You can provide property name (Example : font-family, font-size, font-weight, etc.) with .getCssValue() method to read Its value.

Bellow given example will read values of font-size, color, font-family and text-align properties of "Example Login Page" text.

package Testing_Pack;

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;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class fontTest { 
WebDriver driver = null;

    @BeforeTest
    public void setup() throws Exception {  
  driver = new FirefoxDriver();
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
         driver.get("http://any login page");
    }

 @Test
 public void readFontProperty(){
  //Locate text string element to read It's font properties.
  WebElement text = driver.findElement(By.xpath("//h1[contains(.,'Example Login Page')]"));
  
  //Read font-size property and print It In console.
  String fontSize = text.getCssValue("font-size");
  System.out.println("Font Size -> "+fontSize);
  
  //Read color property and print It In console.
  String fontColor = text.getCssValue("color");
  System.out.println("Font Color -> "+fontColor);
  
  //Read font-family property and print It In console.
  String fontFamily = text.getCssValue("font-family");
  System.out.println("Font Family -> "+fontFamily);
  
  //Read text-align property and print It In console.
  String fonttxtAlign = text.getCssValue("text-align");
  System.out.println("Font Text Alignment -> "+fonttxtAlign);
 }
}

Output of above example Is as bellow.
Font Size -> 26.4px
Font Color -> rgba(102, 102, 102, 1)
Font Family -> "Trebuchet MS",Trebuchet,Verdana,sans-serif
Font Text Alignment -> left