Home > database >  What could be the reason the xpath is returning 0 size
What could be the reason the xpath is returning 0 size

Time:11-30

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

CodePudding user response:

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());
    
    }

  • Related