selenium2+java切换窗口

package exercises;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class demo2 {
    
    private static WebDriver dr = null ;
    private static Set<String> winHandels = null;
    
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "D:\selenium2\chromedriver.exe");
         dr = new ChromeDriver();
        dr.manage().window().maximize();
        dr.get("https://www.baidu.com");
        
        dr.findElement(By.id("kw")).sendKeys("selenium2");
        dr.findElement(By.id("su")).click();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dr.findElement(By.xpath(".//*[@id='1']/h3/a")).click();//弹出新窗口
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
        Set<String> winHandels=dr.getWindowHandles();// 得到当前窗口的set集合
        List<String> it = new ArrayList<String>(winHandels); // 将set集合存入list对象
        dr.switchTo().window(it.get(1));// 切换到弹出的新窗口
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String url=dr.getCurrentUrl();//获取新窗口的url
        System.out.println(url);
        dr.findElement(By.xpath(".//*[@id='ibm-content-wrapper']/header/div[1]/div[2]/ul/li[1]/a")).click();
        dr.switchTo().window(it.get(0));// 返回至原页面
        dr.findElement(By.xpath(".//*[@id='1']/h3/a")).click();
        
    }

}
原文地址:https://www.cnblogs.com/yunman/p/7016827.html