Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 578|回复: 0

selenium2.0 处理各种窗口问题解决方法

[复制链接]
  • TA的每日心情
    奋斗
    2024-4-6 11:05
  • 签到天数: 748 天

    [LV.9]以坛为家II

    2034

    主题

    2092

    帖子

    70万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    705612
    发表于 2021-7-21 10:25:12 | 显示全部楼层 |阅读模式

    selenium2.0处理muti-Windows 、 Frames 、Popup Dialogs

    selenium2.0处理多窗口,弹窗等,只需要调用WebDriver 嵌套类:TargetLocator(driver.switchTo.……),如下:

    driver.switchTo().window("windowName");//target="windowName" ,或者 直接都是使用获取当前窗口句柄来定位

    driver.switchTo().frame("frameName");

    Alert alert driver.switchTo().alert();

    注:当 driver.switchTo().alert()得到alert后,就可以对alert做accept,dismiss,读alert内容,或者填写prompt,适合于alert/confirm/prompts

    下面是具体实例操作代码:

    package mavenSelenium;
    
    import java.util.Set;
    
    import org.openqa.selenium.By;
    import org.junit.*;
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedCondition;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class VariableWindows extends Assert {
    
        protected WebDriver driver;
        @Before
        public void setUp(){
            driver=new FirefoxDriver();
        }
        
        @Test
        public void test()  throws Exception{
            driver.get("file:///C:/Users/jennifer.huang/Desktop/AlertConfirmPromptPage.html");
            //1、操作confirm弹出框
            WebElement e1=driver.findElement(By.id("btnConfirm"));
            e1.click();
            Alert alert11=driver.switchTo().alert();
            if(!alert11.getText().contains("Choose an option.")){
                fail("The confirm should contains [Choose an option.]");
            }
            alert11.accept();
            String expectString="Confirmed";
            verifyResult(expectString);//验证结果Assert.fail
            
            e1.click();
            Alert alert12=driver.switchTo().alert();
            alert12.dismiss();
            expectString="Rejected!";
            verifyResult(expectString); 
            
            //2、操作Alert
            WebElement e2=driver.findElement(By.id("btnAlert"));
            e2.click();
            Alert alert21=driver.switchTo().alert();
            if(!alert21.getText().contains("I'm blocking")){
                fail("Alert should conatins [I'm blocking]");
            }
            alert21.accept();
            expectString="Alert is gone";
            verifyResult(expectString);
            
            //3、操作prompt
            WebElement e3=driver.findElement(By.id("btnPrompt"));
            e3.click();
            Alert alert31=driver.switchTo().alert();
            expectString="selenium2.0";
            alert31.sendKeys(expectString);
            alert31.accept();
            verifyResult(expectString);
            
            //4、操作新Tab
            //4.1 打开新tab  target="_blank"
            WebElement e4=driver.findElement(By.id("linkNewWindow"));
            e4.click();
            changeFocus("百度一下,你就知道");
            System.out.println("当前窗口title:"+driver.getTitle());
            //4.2按钮打开新窗口
            changeFocus("主窗口");
            System.out.println("当前窗口title:"+driver.getTitle());
            WebElement e5=driver.findElement(By.id("btnNewNamelessWindow"));
            e5.click();
            changeFocus("博客园 - 程序员的网上家园");
            System.out.println("当前窗口title:"+driver.getTitle());
            //4.3按钮打开新窗口
            Thread.sleep(5000);
            changeFocus("主窗口");
            WebElement e6=driver.findElement(By.id("btnNewNamedWindow"));
            e6.click();
            changeFocus("博客园 - 程序员的网上家园");
            
            //另外selenium2.0其他操作窗口语句有:
            driver.get("http://www.google.com");//Load a new web page in the current browser window
            driver.navigate().to("http://www.cnblogs.com/jenniferhuang/"); //和driver.get(“url”),都是新载一个页面
            Thread.sleep(2000);
            driver.navigate().back();  //move backwards in  browser’s history:
            Thread.sleep(2000);
            driver.navigate().forward();  //move forwards in  browser’s history:
    
        }
        @After
        public void tearDoown(){
            driver.quit();
        }
        
        /**
         * 验证结果
         * @param expectString
         */
        public void verifyResult(String expectString){
            String resultString=driver.findElement(By.id("output")).getText();
            if(!resultString.contains(expectString)){
                fail("Element [" + By.id("output") + "] should contains [" + expectString + "] ; but now it contains: " + resultString);
            }
        }
        /**
         * 窗口跳转, 通过title来确定要跳到哪个窗口
         * @param windowTitle
         */
        public void changeFocus(String windowTitle){
            for(String handle:driver.getWindowHandles()){
                if(driver.switchTo().window(handle).getTitle().equals(windowTitle)){
                    driver.switchTo().window(handle);
                    break;
                }
            }
        }
    

      上面代码所操作的 页面的源代码示例:AlertConfirmPromptPage.html

    <!DOCTYPE HTML>
    <html lang="zh-cn">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>主窗口</title>
      <script type="text/javascript">
        function output(resultText){
          document.getElementById('output').childNodes[0].nodeValue=resultText;
        }
    
        function show_confirm(){
          var confirmation=confirm("Choose an option.");
          if (confirmation==true){
            output("Confirmed.");
          }
          else{
            output("Rejected!");
          }
        }
    
        function show_alert(){
          alert("I'm blocking!");
          output("Alert is gone.");
        }
        function show_prompt(){
          var response = prompt("What's the best web QA tool?","Selenium");
          output(response);
        }
        function open_window(windowName){
          window.open("http://www.cnblogs.com/",windowName);
        }
        </script>
    </head>
    <body>
    
      <input type="button" id="btnConfirm" onclick="show_confirm()" value="Show confirm box" /></br>
      <input type="button" id="btnAlert" onclick="show_alert()" value="Show alert" /></br>
      <input type="button" id="btnPrompt" onclick="show_prompt()" value="Show prompt" /> </br>
      <a href="http://www.baidu.com" id="linkNewWindow" target="_blank">New Window Link</a></br>
      <input type="button" id="btnNewNamelessWindow" onclick="open_window()" value="Open Nameless Window" /></br>
      <input type="button" id="btnNewNamedWindow" onclick="open_window('Mike')" value="Open Named Window" />
      <br />
      <span id="output">
      </span>
    </body>
    </html>
    

      

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-30 11:22 , Processed in 0.060987 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表