java - Selenium (chromedriver) 中的 Xpath 不会匹配第二个标签

标签 java selenium xpath selenium-chromedriver

尝试使用 java 中的 selenium chromedriver(Chrome 79 版本 79.0.3945.36)匹配网站上的特定范围。跨度嵌套严重,但其本身很简单:

    <span id="nodeval" title="Target XYZ ">Target XYZ </span>

我可以成功使用 text()contains,但我想匹配 @title - 如果可能的话使用 开始于(由于结束动态变化),但这我无法让它正常工作,即使只是直接标签匹配。这是我的测试代码,其中包含、文本、直接标题和使用开头的标题。

    String in_strChapterName = "Target XYZ ";
    List<WebElement> print = myDownloader.getWebDriver().findElements(By.xpath("//span[starts-with(@title,'"+in_strChapterName+"')]"));
    List<WebElement> print2 = myDownloader.getWebDriver().findElements(By.xpath("//span[contains(.,'" + in_strChapterName + "')]"));        
    List<WebElement> print3 = myDownloader.getWebDriver().findElements(By.xpath("//span[text()='" + in_strChapterName + "']"));        
    List<WebElement> print4 = myDownloader.getWebDriver().findElements(By.xpath("//span[@title='"+in_strChapterName+"']"));

    System.out.println("contains matches: "+print2.size());  //1 matches        
    System.out.println("text matches "+print3.size());       //1 matches

    System.out.println("starts-with title matches: "+print.size());  //0 matches
    System.out.println("direct title matches: "+print4.size());      //0 matches

由于我使用示例代码(来自此处: https://www.guru99.com/xpath-selenium.html )几乎 1:1 - 只有标签不是跨度的第一个标签 - 我想知道为什么标签选择对我不起作用...

最佳答案

要匹配标题,您可以使用以下 Locator Strategy :

String in_strChapterName = "Target XYZ";
List<WebElement> print4 = myDownloader.getWebDriver().findElements(By.xpath("//span[contains(@title, '" +in_strChapterName+ "')]"));
System.out.println("direct title matches: "+print4.size()); //1 match

关于java - Selenium (chromedriver) 中的 Xpath 不会匹配第二个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421477/

相关文章:

java - 如何在selenium java中找到复杂(父子)xpath

java - 在java swing中处理事件

java - 同时使用@DataProvider 和@Parameters

java - MetaController 应该观察三个对象

testing - 错误元素当前不可见,因此可能无法与 Selenium 交互

linux - 无法在 Linux 平台上通过 Jenkins 中的 Selenium 启动 Chrome 浏览器

python - 查看标签之间的 html 文本(python、lxml、urllib、xpath)

xml - 如何返回同一级别的子类别?

java - 我可以在迭代时从列表中删除吗?

java - 如何用Java将一维和二维数组写入文本文件