尝试使用 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/