You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何XPath定位返回size为0?Selenium代码问题求助

SVG元素定位返回size为0的问题排查

问题描述

预期代码中List<WebElement>类型的all_states的size返回值为51,但实际返回0。运行代码如下:

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

    }

}

问题原因分析

  • SVG元素XPath命名空间处理错误:SVG属于XML命名空间元素,定位时需统一使用local-name(),原XPath混合使用name()和local-name(),会因为命名空间规则匹配不到元素,应把所有name()替换为local-name()。
  • 等待机制不可靠:强制Thread.sleep(10000)无法保证元素完全渲染,页面可能需要更长加载时间,或元素为动态生成。建议用Selenium显式等待(如WebDriverWait配合ExpectedConditions.visibilityOfAllElementsLocatedBy),确保元素加载完成后再执行定位。
  • DOM结构匹配偏差:实际页面中,子<g>元素的class可能不是region,或层级结构与XPath描述不符。可通过浏览器开发者工具检查DOM,确认元素的id、class和层级是否和XPath一致。

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:00:55