我有以下场景的测试用例:
1)导航到网站。
2)输入Login Credential 3)点击登录。
在我的应用程序中登录后,我为最终用户提供了提示弹出窗口。我使用窗口处理程序来关闭它,但问题是有时selenium运行速度太快,以至于它在可见之前点击它。任何帮助将不胜感激。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(60, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
String mainWindowHandle = driver.getWindowHandle();
driver.switchTo().parentFrame();
wait.until(ExpectedConditions.urlContains("client/default"));
wait.until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d) {
System.out.println(String.format("Window size is %d", d.getWindowHandles().size()));
return (d.getWindowHandles().size() == 1);
}
});
for (String activeHandle : driver.getWindowHandles()) {
if (!activeHandle.equals(mainWindowHandle)) {
driver.switchTo().window(activeHandle);
}
}
driver.findElement(By.xpath(elementLocator("popup_close_button"))).click();
driver.switchTo().window(mainWindowHandle); // switch back to parent window
答案 0 :(得分:0)
参考此代码(摘自 here并修改过):
如果你想让它一直工作,直到弹出出来,然后添加一些代码,如下所示:
int flag=0,wait=0;
while(flag==0 && wait<60){
try{
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
// perform operations on popup
driver.close();///close pop up
driver.switchTo().window(parentWindowHandler); // switch back to parent window
//statements executed successfully, now exit by flag set to 1
flag=1;
}
catch(exception e){//wait for one second
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
wait++;
}
if(wait==60){
JOptionPane.showMessageDialog(null,"Failed to detect pop up after 60 seconds.");
}
}
答案 1 :(得分:0)
发表评论后,声明关闭按钮不会出现在新窗口或标签中。相反,它是登录后的下一页。更新答案以利用预先存在的ExpectedConditions元素,该元素应该(希望)解决问题。
/**
* Performs application Login.
* @param driver WebDriver to act upon.
*/
public void login(WebDriver driver) {
//Perform Login function
//1. Identify the lookup we're going to use for the button.
By closeButtonLookup = elementLocator("popup_close_button");
//2. Set up the Wait object with a reasonable timout value.
WebDriverWait wait = new WebDriverWait(driver, 30);
//3. Try to resolve the close button (from the current page/window/tab) after Selenium believes it to be a viable click target.
WebElement closeButton = wait.until(ExpectedConditions.elementToBeClickable(closeButtonLookup));
System.out.println("Close button valid! Proceeding to click!");
//4. Click the button
closeButton.click();
System.out.println("I clicked the close button!");
//Continue program
}