What could be the reason the xpath is returning 0 size

What could be the reason the xpath is returning 0 size

Problem Description:

I expected the size of the String all_states to return a value 51 but it sends me 0. What could be the reason on this code?

package seleniumsessions;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class SVGElement {

    static WebDriver driver;
    
    public static void main(String[] args) throws InterruptedException {

        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.get("https://petdiseasealerts.org/forecast-map/#/");
        Thread.sleep(10000);
        
        String fullMapXpath = "//*[local-name()='svg' and @id='map-svg']//*[name()='g' and @id ='regions']//*[name()='g' and @class='region']";
        //Thread.sleep(10000);
        
        List<WebElement> all_states = driver.findElements(By.xpath(fullMapXpath));
        System.out.println(all_states.size());

    }

}

I have the above code and i gives me 0

Solution – 1

It is inside an iframe, you have to switch to that iframe and locate the element:

static WebDriver driver;

public static void main(String[] args) throws InterruptedException {

    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
    driver.get("https://petdiseasealerts.org/forecast-map/#/");
    Thread.sleep(3000);

    // switch to iframe     
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath(".//*[starts-with(@id, 'map-instance-')]")));
    
    String fullMapXpath = "//*[local-name()='svg' and @id='map-svg']//*[name()='g' and @id ='regions']//*[name()='g' and @class='region']";

    List<WebElement> all_states = driver.findElements(By.xpath(fullMapXpath));
    System.out.println(all_states.size());

}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject