我从父窗口中单击一个按钮,它将在new(child)窗口中加载查看器,然后在第二个窗口中执行一些操作。在这里,在加载第二个窗口本身之前,脚本尝试执行一些操作,但失败了。如果我放入Thred.sleep
,则操作成功。但我不想使用thread.sleep。我们有什么方法可以等待SECOND / CHILD窗口完全加载其页面。这里的第二个窗口(浏览器)是PDF类型的查看器。下面是我尝试过的代码。
WebElement row = ele.findElement(By.cssSelector("tr[data-ri=\"0\"]"));
row.findElement(By.className("ui-selection-column")).click();
browser.findElement(By.id("frmResults:btnViewer")).click();
Thread.sleep(5000);
Set<String> AllWindowHandles = browser.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
scenario.write("Currently in Parent Window = "+ AllWindowHandles.toArray()[0]);
scenario.write(browser.getCurrentUrl());
scenario.write(browser.getTitle());
String window2 = (String) AllWindowHandles.toArray()[1]; // out of bounds error thrown here
scenario.write("Switching to Child (Viewer) window = "+ AllWindowHandles.toArray()[1]);
browser.switchTo().window(window2);
scenario.write(browser.getCurrentUrl());
scenario.write(browser.getTitle());
WebElement viewer = browser.findElement(By.id("outerDiv"));
assertThat(viewer.isDisplayed()).isTrue();
//browser.close();
scenario.write("Again Switching back to Parent window = "+ AllWindowHandles.toArray()[0]);
browser.switchTo().window(window1);
scenario.write(browser.getCurrentUrl());
scenario.write(browser.getTitle());
已更新
当我尝试在此行上获取子窗口编号时,我得到了错误。
String window2 = (String) AllWindowHandles.toArray()[1];
错误:
java.lang.ArrayIndexOutOfBoundsException: 1
at Steps.Steps.verify_the_test_records_are_displayed_in_the_results_table_in_Search_Results_page(Steps.java:115)
at ?.Then Verify the test records are displayed in the results table in Search Results page(Test.feature:10)
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 30.552 s <<< FAILURE! - in Runner.TestRunner
[ERROR] feature(Runner.TestRunner) Time elapsed: 29.389 s <<< FAILURE!
cucumber.runtime.CucumberException: java.lang.ArrayIndexOutOfBoundsException: 1
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
答案 0 :(得分:1)
您可以使用thread.sleep()
类代替ExpectedConditions
在number of expected windows上添加目标明确的等待:
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.numberOfWindowsToBe;
// we need the above using statements to use WebDriverWait and ExpectedConditions
// first wait for number of windows to be 2:
WebDriverWait wait = new WebDriverWait(browser, 10);
wait.until(ExpectedConditions.numberOfWindowsToBe(2)));
// switch to a new window
String window2 = (String) AllWindowHandles.toArray()[1];
scenario.write("Switching to Child (Viewer) window = "+ AllWindowHandles.toArray()[1]);
browser.switchTo().window(window2);
// wait on some element on the page to be fully loaded
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("outerDiv")));
ExpectedConditions
应等待2个窗口存在,然后再调用String window2 = (String) AllWindowHandles.toArray()[1];
–这应确保browser.getWindowHandles()
返回2
,然后再尝试切换到第二个窗口。