Please post your Web Driver questions in official Web Driver forum

Thursday, June 23, 2011

Selenium Tutorial: Get attribute of an element

With Selenium 1.0

Let us consider Google Search Box for example and its "max length"is to be retrieved.

Using xPath -
        String var = selenium.getAttribute("//input[@name='q']/@maxlength");
        System.out.println(var);

Using css locator -       
       
        String var = selenium.getAttribute("css=input[name='q']@maxlength");
        System.out.println(var);
      
With Selenium 2.0 (WebDriver)       

Using xPath -
        String var = webDriver.findElement(By.xpath("//input[@name='q']")).getAttribute("maxlength")
        System.out.println(var);

Using css locator -       
       
        String var = webDriver.findElement(By.cssSelector("input[name='q']")).getAttribute("maxlength")
        System.out.println(var);
Fork me on GitHub