为什么在 Selenium 测试中 chrome 和 firefox/firebug 的 xpath 定位器不同

Why do the xpath locators differ for chrome and firefox/firebug in Selenium test

在 chrome 我得到一个 xpath 值: //*[@id='user_change_pw_form']/div[3]/span

对于 firebug 中的相同元素,我得到: /html/body/div[2]/form/div[3]/span

为什么我必须像这样分离 xpath 查询才能在 Selenium 测试用例中获得一个相同的元素:

switch (System.getProperty("test.driver")) 
        {
            case "chrome":
            case "html":
                text = driver.findElement(By.xpath("//*[@id='user_change_pw_form']/div[3]/span")).getText();


            case "gecko":
                text = driver.findElement(By.xpath("/html/body/div[2]/form/div[3]/span")).getText(); 
                break;

        }

虽然相应的对应项给出了错误的浏览器 "Unable to locate element",但两个 xpath 查询在两个浏览器控制台中都有效。

提前致谢!

尝试编写您自己的 xPaths / CSS 选择器,而不是依赖基于浏览器的选择器。 link 可以帮助您 learn/write 您自己的选择器。

我还建议使用 css 选择器而不是 xpath,因为它们更具可读性。

firefox 有绝对的 xpath,无法处理 chrome 的 xpath。

感谢@noor 和@Kenil Fadia