如何使用Selenium WebDriver和Java关闭特定的窗口?

2023年 9月 8日 33.4k 0

We can close a specific window with Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.

The getWindowHandle method is used to store the window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code.

By default, the driver object can only access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
public class CloseSpecificWindow {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:Usersghs6korDesktopJavachromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://secure.indeed.com/account/login");
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//window handle of parent window
String m = driver.getWindowHandle();
driver.findElement(By.id("login-google-button")).click();
// store window handles in Set
Set w = driver.getWindowHandles();
// iterate window handles
for (String h: w){
// switching to each window
driver.switchTo().window(h);
String s= driver.getTitle();
// checking specific window title
if(s.equalsIgnoreCase("Sign in - Google Accounts")){
System.out.println("Window title to be closed: "+ driver.getTitle());
driver.close();
}
}
// switching parent window
driver.switchTo().window(m);
driver.quit();
}
}

登录后复制

输出

如何使用Selenium WebDriver和Java关闭特定的窗口?

以上就是如何使用Selenium WebDriver和Java关闭特定的窗口?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论