Selenium WebDriver—切换窗口和iFrame
1.切换窗口
package jssd;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import java.util.Set;
/**
* @author 96510
* @version 1.0
* @date 2021/7/2
*/
public class SwitchWindows {
WebDriver driver = new ChromeDriver();
String url = "https://www.baidu.com/";
@Before
public void setUp() throws Exception {
driver.manage().window().maximize();
Thread.sleep(8);
}
@Test
public void name() throws Exception {
driver.get(url);
String parentHandle = driver.getWindowHandle();
System.out.println("主窗口为" + parentHandle);
driver.findElement(By.xpath("//span[@class='title-content-title'and contains(text(),'刺杀海地总统嫌犯所用凶器曝光')]")).click();;
String Handle = driver.getWindowHandle();
System.out.println("新打开的窗口为" + Handle);
Set<String> Handles = driver.getWindowHandles();
for (String hd : Handles) {
if (!hd.equals(parentHandle)) {
driver.switchTo().window(hd);
break;
}
}
Thread.sleep(3000);
driver.close();
driver.switchTo().window(parentHandle);
}
@After
public void tearDown() throws Exception {
// driver.quit();
}
}
2.切换iFrame
package jssd;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class SwitchFrime {
WebDriver driver = new ChromeDriver();
String url = "https://jqueryui.com/";
@Before
public void setUp() throws Exception {
driver.manage().window().maximize();
Thread.sleep(8);
}
@Test
public void name() throws Exception {
driver.get(url);
driver.findElement(By.xpath("//*[@id=\"sidebar\"]/aside[2]/ul/li[10]/a")).click();
driver.switchTo().frame(0);
driver.findElement(By.xpath("//span[@class='ui-selectmenu-text' and contains(text(),'Medium')]")).click();
}
@After
public void tearDown() throws Exception {
}
}
3.JavaScript弹窗处理
package jssd;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class SwitchAlert {
WebDriver driver = new ChromeDriver();
String url = "file:///E:/Chrome/8PracticePage.html";
@Before
public void setUp() throws Exception {
driver.manage().window().maximize();
Thread.sleep(8);
}
@Test
public void name() throws Exception {
driver.get(url);
driver.findElement(By.id("name")).sendKeys("测试");
driver.findElement(By.id("alertbtn")).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
alert.accept();
}
@After
public void tearDown() throws Exception {
}
}