如何使用XPATH在JAVA中搜索带有Selenium Testing类的span

aly*_*00r 0 java selenium xpath

我正在编写一段代码,希望我选择类的跨度amountCharged并获取该跨度的值以根据模拟值测试它.我面临的问题是我似乎无法选择span使用XPath.我尝试了多种方法仍然失败,我继续W3SchoolsStackoverflow问题,但无法确定语法.

以下是我面临的错误:

org.openqa.selenium.TimeoutException: Timed out after 60 seconds waiting for text ('£163.06') to be present in element found by `By.xpath:`

 //span[contains(@class, 'amountCharged')]
Run Code Online (Sandbox Code Playgroud)

正如你可以看到我想使用//span[contains(@class,'amountCharged')]XPATH,同样的问题用"

/descendant::span[contains(@class, 'amountCharged')]
Run Code Online (Sandbox Code Playgroud)

从父母DIV开始的HTML是:

    <div class="panelMessage instructional" params="">    Total:         
 <span class="amountCharged">£163.06</span> quoted on          
<span class="reservationTime">Tue, 29 Nov 2011 15:46 GMT</span> . </div>
    </div>        
<div class="panelContent hideFocus noneBlock  " tabindex="-1" data-  context="panelContent">
Run Code Online (Sandbox Code Playgroud)

JAVA代码是:

   private static void elementShouldContain(String locator, String value, String errorMessage, long timeout) {
    String xpath = buildLocator(locator, "");
    WebDriverWait customWait = new WebDriverWait(webDriverInstance, timeout / 1000);
    try {
    customWait.until(ExpectedConditions.textToBePresentInElement(By.xpath(xpath), value));
    } catch (Exception e) {
        // Handles the specific exception, except that the message is null, in which case throws a regular SeleniumException
        if (errorMessage != null)
            throw new CustomSeleniumException(errorMessage, e);
        else
            throw new SeleniumException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么,请帮忙.

谢谢

Sai*_*fur 5

要记住这一点:

  1. 测试xpathFirebug的Chrome调试器并不一定意味着它将selector唯一地返回目标元素.可能有一些其他元素隐藏了相同的选择器,并且webdriver在这种情况下将无法找到目标元素.出于调试目的,findElements请查看它返回的元素数量.
  2. 元素加载问题如:可见性也可能是另一个问题.这就是为什么你需要确保元素存在和可见.使用显式等待

试试以下 xpaths

//span[@class='amountCharged']
Run Code Online (Sandbox Code Playgroud)

如果班级不是唯一的,你想找到 span依赖于div的类,则可以执行以下操作:

//div[contains(@class,'panelMessage ')]//span[@class='amountCharged']
Run Code Online (Sandbox Code Playgroud)

  • @ alyn000r如果您关心得到答案,请显示_complete_ HTML和测试代码.我们不喜欢在黑暗中(我想你也不会). (3认同)