我正在尝试为这种情况找到合适的 ExpectedConditions 方法。我有一个图表,我想在重新排序图表后检查每一行中的文本。问题是,当图表刷新时,文本仍然存在,只是变灰了。因此,当我单击一个按钮让图表重新排序,然后立即查找我要查找的文本时,测试失败,因为文本尚未更改。我无法使用 visibilityOfElementLocated,因为当图表刷新时元素仍然可见,我只是在等待元素发生变化。
不确定这是否有意义!!这是一个很难解释的问题。
一些背景知识:我正在使用 Selenium Java 并使用 Chrome 进行测试。到目前为止,这是我的方法。它工作正常,我只需要弄清楚如何让程序等待足够长的时间让图表在不使用 sleep 语句的情况下刷新。
非常感谢大家!我知道这还不够清楚,但如果您需要任何说明,请告诉我。
public void Check_for_text_in_column(String text, String row, String column)
{
By by = By.xpath("//*[@id=\"table_Table_table_ktg\"]/tbody/tr[" + row + "]/td[" + column + "]/div/div/span");
WebDriverWait wait = new WebDriverWait(getWebDriver(), WAIT_TIME);
//This is the line that I need to change:
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
if(!element.getText().equals(text))
{
fail("\nDid not find text: " + text + "\nFound text: " + element.getText() + "\n");
}
}
干杯!
最佳答案
可以替换
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
与
WebElement element = wait.until(ExpectedConditions.textToBePresentInElement(by, text));
编辑:
您的WAIT_TIME
是您等待的超时时间。
如果在根据您的WAIT_TIME
超时之前预期条件没有返回true
,则element
将为null
.
所以,您的支票可能看起来像这样:
if(element == null)
{
fail("\nDid not find text: " + text + "\nFound text: " + element.getText() + "\n");
}
编辑:
也许另一种选择可能是这样的:
public void Check_for_text_in_column(String text, String row, String column)
{
By by = By.xpath("//*[@id=\"table_Table_table_ktg\"]/tbody/tr[" + row + "]/td[" + column + "]/div/div/span");
WebDriverWait wait = new WebDriverWait(getWebDriver(), WAIT_TIME);
// your original find
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
// flag to set when text is found, for exiting loop
boolean hasText = false;
// counter for # of times to loop, finally timing out
int tries = 0;
// until text is found or loop has executed however many times...
while (hasText == false && tries < 20) {
// get the element
element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
// if text is not present, wait 250 millis before trying again
if(!element.getText().equals(text){
Thread.sleep(250);
tries++;
}
else{
// text found, so set flag to exit loop
hasText = true;
}
}
if(!element.getText().equals(text))
{
fail("\nDid not find text: " + text + "\nFound text: " + element.getText() + "\n");
}
}
我知道您说过您不想要 sleep
语句,但我假设您的意思是您只是不想要一个不必要的长语句。甚至 ExpectedConditions
也在内部使用 sleep
。它们在轮询更改之间 hibernate
几毫秒 - 这正是它所做的,只是没有 ExpectedCondition
类型包装器。
关于java - 等待图表刷新,selenium Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027199/