Sachin Sharma
Sachin Sharma

Reputation: 15

Unable to find expected number of element in selenium

When search element in chrome using inspect element search box by xpath '//*[contains(@id,'a')]' then total found element number is 43 but when use the same xpath in selenium code then it shows only 37 element found.

below is selenium code. I even tried looking into frame but still did not get expected result

driver.get("http://facebook.com");
        //System.out.println(driver.findElements(By.tagName("iframe")).size());
        List<WebElement> a = driver.findElements(By.xpath("//*[contains(@id,'a')]"));
        System.out.println(a.size());
        driver.switchTo().frame(0);
        List<WebElement>b=driver.findElements(By.xpath("//*[contains(@id,'a')]"));
        System.out.println(b.size());
        driver.switchTo().parentFrame();
        driver.switchTo().frame(1);
        List<WebElement>c=driver.findElements(By.xpath("//*[contains(@id,'a')]"));
        System.out.println(c.size());
        driver.switchTo().parentFrame();

Upvotes: 0

Views: 153

Answers (1)

S A
S A

Reputation: 1783

  • The reason you are getting a different number of nodes is in the DOM there are iframe elements. There is even an iframe inside an iframe.

  • When you are searching in the chrome dev tools, it shows all elements, including the ones inside the frames.
    But when you are using selenium, it is not accessing the DOM inside the frames. That is why you are getting fewer elements in selenium.

  • When you are switching the frames you are not actually searching it in all the second-degree frames available in the page.

I've identified the frames in which the missing elements are. Just don't go back to the parent frame and go another level deeper and you'll find all your elements.

Try the following code and it will give you the desired result.

    driver.get("https://www.facebook.com");

    List<WebElement> list = driver.findElements(By.xpath("//*[contains(@id,'a')]"));
    System.out.println("Main Page: "+list.size());

    //driver.switchTo().frame("captcha-recaptcha");
    driver.switchTo().frame(0);
    List<WebElement> list2 = driver.findElements(By.xpath("//*[contains(@id,'a')]"));
    System.out.println("In the iFrame: "+list2.size());

    //driver.switchTo().frame(driver.findElement(By.cssSelector("body > div.g-recaptcha > div > div > iframe")));
    driver.switchTo().frame(0);
    List<WebElement> list3 = driver.findElements(By.xpath("//*[contains(@id,'a')]"));
    System.out.println("In the second iFrame: "+list3.size());

    System.out.println("Full count: "+(list.size()+list2.size()+list3.size()));

Upvotes: 0

Related Questions