Java Selenium:无法在第二个循环中获取动态文本

Java Selenium:无法在第二个循环中获取动态文本,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我试图获取动态文本并显示它,它在while循环中执行。它成功显示文本,但在下一次迭代中显示不一致 在单击下拉元素之后立即给予隐式等待,以便在UI上更新数据。但我仍然没有得到想要的输出。还有什么我不知道的,请告诉我。 另外,当我打印arraylist res_arr的索引时,它会输出[]。 我的代码: 第一个问题是您正在使用hcdata执行所有三个getText()操作 尝试以下更改: String freq_no = hcdata.getText().toString(); 致: 及 致: 第

我试图获取动态文本并显示它,它在while循环中执行。它成功显示文本,但在下一次迭代中显示不一致

在单击下拉元素之后立即给予隐式等待,以便在UI上更新数据。但我仍然没有得到想要的输出。还有什么我不知道的,请告诉我。 另外,当我打印arraylist res_arr的索引时,它会输出[]。 我的代码:


第一个问题是您正在使用
hcdata
执行所有三个
getText()
操作

尝试以下更改:

String freq_no = hcdata.getText().toString();
致:

致:

第二个问题是隐式等待仅等待元素出现,如果元素已经在页面上,但没有值,它将立即返回

您需要的是显式等待。比如:

sl.getOptions().get(i).click();

By hcdataBy = By.xpath("//form/div/div[3]/div[2]/div[1]/p");
//this would wait up to 10 seconds for the wait condition. Change the 2nd parameter if longer or shorter would be better.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(new ExpectedCondition<Boolean>(){
    public Boolean apply(WebDriver d) {
        return d.findElement(hcdataBy).getText().length() > 0;
    }
});
取决于加载数据时
getText()
的实际值


<强>隐式等待< /强>的另一件事是,一旦你设置它,你的测试将使用它直到你改变它。因此,如果在循环开始时设置它,那么从那时起,每次测试找到元素时,它都会使用隐式等待。这可能会导致一些混乱的行为,因为很难跟踪代码中何时设置了隐式等待。出于这个原因,对于其他一些计时问题和bug,我建议只使用显式等待,而不是隐式等待,我建议您使用fluent wait等待,直到文本不为空,并给出超时。或者您可以创建helper方法,在结果仍然为空时重试,例如(!HCdata | | timeout not reacted){将查找元素的代码放在这里}更改隐式等待和findElement组合,并使用WebdriverWait

WebdriverWait wait=new WebdriverWait(webDriver,timeoutingseconds);wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(yourxpath))嗨,它工作了。添加显式等待,使用apply方法对我有效,谢谢:)
String freq_no = hcdata.getText().toString();
String freq_no = freq.getText().toString();
String DT_no = hcdata.getText();
String DT_no = DT.getText();
sl.getOptions().get(i).click();

By hcdataBy = By.xpath("//form/div/div[3]/div[2]/div[1]/p");
//this would wait up to 10 seconds for the wait condition. Change the 2nd parameter if longer or shorter would be better.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(new ExpectedCondition<Boolean>(){
    public Boolean apply(WebDriver d) {
        return d.findElement(hcdataBy).getText().length() > 0;
    }
});
wait.until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElementLocated(hcdata, "")));