使用selenium处理弹出窗口

我有一种情况,点击链接网页打开一个弹出窗口。 弹出窗口打开后,焦点位于弹出窗口中,主窗口被禁用。 我无法将控件转移到弹出窗口。 请查看以下代码。

driver.findElement(By.linkText("Click me")).click();// when this line of code is reached then a popup window opens. System.out.println("After Clicking me"); // After the popup window opens this line of code is never executed. 

我无法将控件从父窗口传输到弹出窗口。 我知道以下命令。

 driver.switchTo().window("popup window"); 

但它没有多大帮助。 请帮帮我。

这是我需要使用以下弹出窗口时关闭它然后返回主窗口的代码。 当然,为了这个答案的目的,它已被简化。 它保持原始窗口(主要)的句柄,因此它可以在其他窗口之间产生差异。

它需要一个显式的WebDriverWait,因为我在开发期间确实遇到了代码在窗口实际打开之前运行的问题,所以这可能不是一个理想的条件,

 function manipulatePopUp(final WebDriver driver, final WebDriverWait wait) { final String mainWindowHandle = driver.getWindowHandle(); driver.findElement(By.id("linkThatOpensPopUp")).click(); wait.until(new ExpectedConditions() { @Override public Boolean apply(WebDriver d) { return (d.getWindowHandles().size() != 1); } }); for (String activeHandle : driver.getWindowHandles()) { if (!activeHandle.equals(mainWindowHandle)) { driver.switchTo().window(activeHandle); } } driver.close(); driver.switchTo().window(mainWindowHandle); } 

driver.findElement(By.linkText(“Click me”))。click(); //当到达这行代码时,会打开一个弹出窗口。

System.out.println(“点击我之后”); //弹出窗口打开后,这行代码永远不会执行。

从不执行代码行,因为进程正在等待处理弹出窗口。

getWindowHandles()在这种情况下正常工作。

例:

 //handle of the master window before clicking the link String master = driver.getWindowHandle(); driver.findElement(By.linkText("Click me")).click(); //logic for waiting for the popup, checking the size to become greater than 1 or breaking after sometime to avoid the infinite loop. int timeCount = 1; do { driver.getWindowHandles(); Thread.sleep(200); timeCount++; if ( timeCount > 50 ) { break; } } while ( driver.getWindowHandles().size == 1 ); //Assigning the handles to a set Set handles = driver.getWindowHandles(); //Switching to the popup window. for ( String handle : handles ) { if(!handle.equals(master)) { driver.switchTo().window(handle); } } 

现在驱动程序切换到弹出窗口。 如果弹出窗口有框架,则需要在识别框架中的元素之前切换到框架。

 public class socialSignOn extends masterBaseClassNewSiteStage { @Test public void testSocialSignOn() throws Throwable { openParticularUrl("/my-lfc/join/user-details?user_type=free"); driver.findElement(By.cssSelector("#socialSignOn > div.left.socialLogin.googleButton")).click(); String MainWindow = driver.getWindowHandle(); for (String activeHandle : driver.getWindowHandles()) { if (!activeHandle.equals(MainWindow)) { driver.switchTo().window(activeHandle); } } driver.findElement(By.cssSelector("#Email")).sendKeys(""); driver.findElement(By.cssSelector("#next")).click(); pauseFiveSeconds(); driver.findElement(By.cssSelector("#Passwd")).sendKeys(""); driver.findElement(By.cssSelector("#signIn")).click(); pauseOneSecond(); driver.switchTo().window(MainWindow); pauseTenSeconds(); closeDriver(); } } 
 // delay : max number of seconds new WebDriverWait(driver, delay * 1000).until(ExpectedConditions.alertIsPresent()); drive`enter code here`r.switchTo().alert().accept();