Selenium (chromedriver) 中的 Xpath 与第二个标签不匹配



试图将网站上的特定范围与 Java 中的硒铬驱动程序(Chrome 79 版本 79.0.3945.36(匹配。跨度大量嵌套,但本身很简单:

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

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

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

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

要匹配标题,您可以使用以下定位器策略:

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

相关内容

最新更新