user2061466 user2061466 - 14 days ago 7
CSS Question

Selenium WebDriver - getCssValue() method

I am doing a exercise to use cssGetValue method to retrieve the value from a particular web element's CSS property.

I have 2 questions:


  1. why the cssGetValue method returned value 13px, which web element does the method actually referenced.
    1a. I want to get CSS property for section labeled as "By ID". how should I modify my code so I can get CSS property value for id="by-id" section?

  2. I used driver.close() method, but it won't close the browser after the script finished. Please explain to me why driver.close() method didn't work in this case.

    Here is my code fragment:

    package wd_findElementBy;

    import java.util.List;

    import org.junit.Test;

    import org.junit.Before;

    import org.junit.After;


    import org.openqa.selenium.By;

    import org.openqa.selenium.WebDriver;

    import org.openqa.selenium.WebElement;

    import org.openqa.selenium.firefox.FirefoxDriver;


    public class SearchWebElements
    {

    WebDriver driver = new FirefoxDriver();
    private String baseUrl= "http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example";

    @Test
    public void findElements(){
    driver.get(baseUrl);

    try{
    List<WebElement> elements = driver.findElements(By.id("by-id"));
    System.out.println("number of elements: " + elements.size());

    for(WebElement ele : elements){
    System.out.println(ele.getTagName());

    System.out.println("get the text for web element with id='by-id' ");
    System.out.println("------------------------------------------------------------");
    System.out.println(ele.getText());
    System.out.println("------------------------------------------------------------");
    System.out.println(ele.getAttribute("id"));
    System.out.println(ele.getCssValue("font-size"));

    }
    }

    finally{
    //driver.close();
    driver.quit();
    }


    }

    }


Answer

Yes, all correct.

Here's a screenshot of where to find font-size through Firebug.

enter image description here

Since the ids are supposed to be unique (at least for this page), you don't need findElements to find a list of elements with id by-id and loop through, instead, you use findElement to get the element directly.

try{
        WebElement byId = driver.findElement(By.id("by-id"));

        System.out.println(byId.getTagName());

        System.out.println("get the text for web element with id='by-id' ");
        System.out.println("------------------------------------------------------------");
        System.out.println(byId.getText());
        System.out.println("------------------------------------------------------------");
        System.out.println(byId.getAttribute("id"));
        System.out.println(byId.getCssValue("font-size"));
    }
}