【问题标题】:Xpath in Selenium (chromedriver) wont match second tagSelenium (chromedriver) 中的 Xpath 与第二个标签不匹配
【发布时间】:2019-12-20 07:38:11
【问题描述】:

尝试使用 java 中的 selenium chromedriver(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

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

【问题讨论】:

  • 我尝试在 XSLT-1.0 中重现您的问题,结果是所有四个表达式都按预期工作。

标签: java selenium xpath selenium-chromedriver


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 2014-02-02
    • 2016-09-08
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多