简体   繁体   English

为什么 Selenium 不能通过 xpath 找到元素?

[英]Why doesn't Selenium find element by xpath?

When I run the following program, why is '0' printed to the console?当我运行以下程序时,为什么控制台会打印“0”? I expected '1' to be printed since I expected the findElements() method to find a link using the xpath.我希望打印“1”,因为我希望findElements()方法使用 xpath 查找链接。 Is the xpath expression incorrect? xpath 表达式不正确吗? I got the expression using Firefox, Firebug, and Firepath, by selecting the link element and copying the given xpath.通过选择链接元素并复制给定的 xpath,我使用 Firefox、Firebug 和 Firepath 获得了表达式。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.List;

public class SeleniumSearch {
    static WebDriver driver = new FirefoxDriver();

    public static void main(String[] args) {

        try {
            driver.get("http://www.google.co.uk/");
            submitSearch("selenium");
            getHit();
        }
        finally {
            driver.close();
        }
    }

    static void submitSearch(String search) {
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys(search);
        searchBox.submit();
    }

    static void getHit() {
        List<WebElement> hits = driver.findElements(By.xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a"));
        System.out.println(hits.size());
    }
}

Firepath 给出的 xpath 的屏幕截图

尝试将以下内容作为 xpath 而不是实际路径: //*[@id="rso"]/div[2]/div[1]/div/h3/a

xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a")

That's wrong work with xpath, one little change on website and your code wouldn't work!使用 xpath 是错误的,在网站上稍作改动,您的代码将无法工作! try to do it more dynamic find the closest id or tag name and continue from there, can you share your html source?尝试更动态地找到最接近的 id 或标签名称并从那里继续,你能分享你的 html 源代码吗?

I would use a simple xpath like html/body//h3/a .我会使用一个简单的xpath,比如html/body//h3/a You can also use FirePath extension of FireBug to build and evaluate xpaths.您还可以使用 FireBug 的 FirePath 扩展来构建和评估 xpath。

我可以想出的最简单的 xpath 用于谷歌搜索中的第一个链接:

(//h3/a)[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM