从日期选择器中选择日期后,单击“查看报告”按钮,然后花一些时间来生成报告,然后下载报告。。我的以下代码正常工作,但没有错误使用流畅的等待,而不是Thread.sleep(20000),(下面代码的最后一行)。对于流利或明确的等待,我要求等待什么条件?还希望通过断言来验证文件是否已下载。任何帮助将不胜感激。
public void generateReport() throws Exception {
clickDatePicker.click();
log.info("Select the Date from datepicker");
Select month = new Select(selectMonth);
month.selectByValue("0");
log.info("Selected the Month from datepicker");
Select year = new Select(selectYear);
year.selectByValue("2020");
log.info("Selected the Year from datepicker");
act.moveToElement(selectDate).click().build().perform();
buttonViewReport.click();
log.info("Finally clicked on Get Report button ");
Thread.sleep(20000);
}
答案 0 :(得分:0)
检查以下方法,该方法将确保脚本将等待下载开始(方法调用中指定的最长分钟数)
public void waitUntilDownloadStarted(WebDriver driver, int maxWaitTimeInMinutes) throws InterruptedException {
// Store the current window handle
String mainWindow = driver.getWindowHandle();
// open a new tab
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.open()");
// switch to new tab
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// navigate to chrome downloads
driver.get("chrome://downloads");
Instant startTime = Instant.now();
int elapsedTime = (int) Duration.between(startTime, Instant.now()).toMinutes();
// wait until the download is started
while ( (Long)js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelectorAll('#downloadsList downloads-item').length") == 0) {
Thread.sleep(1000);
elapsedTime = (int) Duration.between(startTime, Instant.now()).toMinutes();
if (elapsedTime > maxWaitTimeInMinutes) {
break;
}
}
// close the downloads tab2
driver.close();
// switch back to main window
driver.switchTo().window(mainWindow);
}
经过如下测试。
waitUntilDownloadStarted(driver, 10);
答案 1 :(得分:0)
是否显示出已生成下载内容?或检查HTML中的任何更改。那么您可以使用以下代码等待更改出现。
WebDriverWait wait=new WebDriverWait(driver, 20000);
wait.until(ExpectedConditions.numberOfElementsToBe(locator, number));
其中20000是时间(以毫秒为单位)