selenium webdriver - 使用foreach关闭除一个特定子窗口之外的所有子窗口(java)

时间:2016-05-27 20:31:56

标签: eclipse selenium

  1. 启动popuptest.com
  2. 点击'Multi-PopUp Test#2'
  3. 打印已打开的窗口数
  4. 关闭所有窗口,但不关闭父窗口和背景颜色为“#00C957”的子窗口
  5. 打印页面URL和标题以及关闭的窗口
  6. 拍摄打开的窗口的快照。
  7. 请任何人帮我编码:

    Iterator

1 个答案:

答案 0 :(得分:0)

此代码运行正常。

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Pop_up_Child_Window_pop_up_example_4 
{

    public static void main(String[] args) throws InterruptedException
    {
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://popuptest.com/popuptest12.html");

        Set<String> windowIDs = driver.getWindowHandles();
        Thread.sleep(2000);

        System.out.println("number of windows opened --> "+ windowIDs.size());

        Iterator<String> it = windowIDs.iterator();
        String parent  = it.next();

        // child pop 1
        String child  = it.next();
        driver.switchTo().window(child);
        driver.manage().window().maximize();

        WebElement attri = driver.findElement(By.xpath("//body[@bgcolor='#3D59AB']"));
        String bgOfChild = attri.getAttribute("bgcolor");
        System.out.println(bgOfChild);
        if(!bgOfChild.equals("#FF6633"))
        {
            driver.close();
        }

        // child pop 2
        String child2  = it.next();
        driver.switchTo().window(child2);
        driver.manage().window().maximize();

        WebElement attri2 = driver.findElement(By.xpath("//body[@bgcolor='#FF6633']"));
        String bgOfChild2 = attri2.getAttribute("bgcolor");
        System.out.println(bgOfChild2);
        if(!bgOfChild2.equals("#FF6633"))
        {
            driver.close();
        }

        // child pop 3
        String child3  = it.next();
        driver.switchTo().window(child3);
        driver.manage().window().maximize();

        WebElement attri3 = driver.findElement(By.xpath("//body[@bgcolor='#00C957']"));
        String bgOfChild3 = attri3.getAttribute("bgcolor");
        System.out.println(bgOfChild3);
        if(!bgOfChild3.equals("#FF6633"))
        {
            driver.close();
        }

    }

}