TESTEVERYTHING

Friday, 12 October 2012

Count elements/links on page using webdriver

Sometimes we need to count links on page. Here we are counting the elements on page. We use the same method for any type of element like link, span,button just use html tag of that element in xpath.


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.
WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
   


        String  baseUrl = "https://www.google.co.in/";
            System.out.println("firefox");
            FirefoxProfile firefoxprofile = new FirefoxProfile();
            firefoxprofile.setPreference("capability.policy.default.Window.QueryInterface", "allAccess"); 
            firefoxprofile.setPreference("capability.policy.default.Window.frameElement.get","allAccess"); 
            firefoxprofile.setAssumeUntrustedCertificateIssuer(false);
            DesiredCapabilities capability = DesiredCapabilities.firefox();
            capability.setCapability(FirefoxDriver.PROFILE, firefoxprofile);
            capability.setBrowserName("firefox");
            capability.setPlatform(org.openqa.selenium.Platform.ANY);
            driver = new FirefoxDriver(capability);

       driver.get(baseUrl);
        int i=0;
        List<WebElement> allElements = driver.findElements(By.xpath("//*"));

        for (WebElement Element : allElements) {
            i = i+1;
            System.out.println(Element.getTagName());
        System.out.println(Element.getText());
        }
        System.out.println("total objects founds " + i);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
here we are finding all the elements on page
List<WebElement> allElements = driver.findElements(By.xpath("//*")); 
in case if you want to count all the links on page then use below code
List<WebElement> allElements = driver.findElements(By.xpath("//a")); 

Or if you want to count all buttons on the page the use below code

List<WebElement> allElements = driver.findElements(By.xpath("//BUTTON")); 

No comments:

Post a Comment

Which one is right ?

Translate







Tweet