我正在编写一段代码,希望我选择类amountCharged
的范围并获取该范围的值以根据模拟值对其进行测试。我面临的问题是我似乎无法使用span
选择XPath
。我尝试了多种方法但仍然失败,我继续 W3Schools 和 Stackoverflow 问题,但无法确定语法。
以下是我面临的错误:
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')]
正如您所看到的,我正在尝试将//span[contains(@class,'amountCharged')]
用作XPATH
,与使用&#34相同的问题;
/descendant::span[contains(@class, 'amountCharged')]
从父母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">
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);
}
}
我错过了什么,请帮忙。
谢谢
答案 0 :(得分:5)
要牢记这一点:
xpath
并不一定意味着selector
将唯一地返回目标元素。可能有一些其他元素隐藏了相同的选择器,webdriver
将无法找到该情况下的目标元素。出于调试目的,使用findElements
a查看它返回的元素数。尝试关注xpaths
//span[@class='amountCharged']
如果课程不是唯一的,并且您希望根据div找到span
,则可以执行以下操作:
//div[contains(@class,'panelMessage ')]//span[@class='amountCharged']
答案 1 :(得分:1)
根据您提到的错误,我认为您在textToBePresentInElement 下使用textToBePresentInElementLocated或ExpectedConditions class或其他相关方法。
您也可以这样做:
1-使用Explicit Wait等待元素的可见性
2-检索文本
3-断言/比较文本的值:'£163.06'。
您可以按顺序尝试以下所有代码:
String text_in_panel=null;
try{
//waiting 20 seconds for the visibility of the element
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class, 'panelMessage')]/span[1]")));
//Retrieving the text from the element
text_in_panel = element.getText();
}catch(Throwable e){
System.err.println("Element is not visible: "+e.getMessage());
}
//Comparing the text with the hard-coded value
if(text_in_panel.equals("£163.06"))
System.out.println("Text matches");
else
System.err.println("Text doesn't match");
[或者您可以通过导入import junit.framework.Assert使用Assert类来断言值而不是比较它们;]
//Assert the text with the hard-coded value
try{
Assert.assertEquals(text_in_panel, "£163.06");
System.out.println("Text matches");
}catch(Throwable e){
System.err.println("Text doesn't match");
}