如何使用Selenium java在浏览器中的两个窗口之间切换 [英] How to switch between two windows in browser using Selenium java

查看:21
本文介绍了如何使用Selenium java在浏览器中的两个窗口之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Selenium 自动化.在此,当我单击当前窗口中的链接时,会打开一个新窗口.我只想将控件切换到新窗口.但我不能这样做.实际上,新窗口是一个自动生成的窗口.即动态生成链接.帮帮我的朋友...

I'm working with Selenium Automation. In this, When i click a link in a current window, a new window opens. I just want to switch the control to the new window. But i can't do this.Actually the new window is an auto-generated one. That is, link will be generated dynamically. Help me friends...

推荐答案

在窗口之间切换我们有方法.

To switch between windows we have method.

driver.switchTo().window("window name") 

要获取不同的窗口句柄,我们有方法.

To get the different windows handle, we have method.

driver.getWindowHandles()

示例:

    File file = new File("G:\Selenium\All_Jars\chromedriver.exe");
    System.setProperty("webdriver.chrome.driver",file.getAbsolutePath() );
    driver = new ChromeDriver();

    //Maximize the window
    driver.manage().window().maximize();

    driver.get("http://www.rediff.com/");

    //Get all window handles
    Set<String> allHandles = driver.getWindowHandles();

    //count the handles Here count is=2
    System.out.println("Count of windows:"+allHandles.size());      

    //Get current handle or default handle
    String currentWindowHandle = allHandles.iterator().next();
    System.out.println("currentWindow Handle"+currentWindowHandle);

    //Remove first/default Handle
    allHandles.remove(allHandles.iterator().next());

    //get the last Window Handle
    String lastHandle = allHandles.iterator().next();
    System.out.println("last window handle"+lastHandle);

    //switch to second/last window, because we know there are only two windows 1-parent window 2-other window(ad window)
driver.switchTo().window(lastHandle);
    System.out.println(driver.getTitle());
    driver.findElement(By.tagName("body")).click();

这篇关于如何使用Selenium java在浏览器中的两个窗口之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆