WebDriverAPI(9)

  操作JavaScript的Alert窗口

  测试网址代码 

  <html>
    <head>
      <title>你喜欢的水果</title>
    </head>
    <body>
      <input id='button' type='button' onclick="alert('这是一个alert弹窗');" value='单击此按钮,弹出alert弹出窗'/></input>
    </body>
  </html>

  Java语言版本API实例 

  @Test
  public void testHandleAlert() {
    driver.manage().window().maximize();
    driver.get(url);
    WebElement button = driver.findElement(By.xpath("//input"));
    button.click();
    try {
      //使用driver.switchTo.alert()方法获取Alert对象
      Alert alert = driver.switchTo().alert();
      //断言判断
      Assert.assertEquals("这是一个alert弹窗", alert.getText());
      alert.accept();
    } catch (NoAlertPresentException exception) {
      Assert.fail("尝试操作的alert框未被找到");
      exception.printStackTrace();
    }
  }

  操作JavaScript的confirm窗口

  测试网址代码 

  <html>
    <head>
      <title>你喜欢的水果</title>
    </head>
    <body>
      <input id='button' type='button' onclick="confirm('这是一个confirm弹窗');" value='单击此按钮,弹出confirm弹出窗'/></input>
    </body>
  </html>

  Java语言版本API实例 

  @Test
  public void testHandleconfirm() {
    driver.manage().window().maximize();
    driver.get(url);
    WebElement button = driver.findElement(By.xpath("//input"));
    button.click();
    try {
      Alert alert = driver.switchTo().alert();
      Assert.assertEquals("这是一个confirm弹窗", alert.getText());
      alert.accept();
    } catch (NoAlertPresentException exception) {
      Assert.fail("尝试操作confirm未被找到");
      exception.printStackTrace();
    }
  }

  操作JavaScript的prompt窗口

  测试网址代码 

  <html>
    <head>
      <title>你喜欢的水果</title>
    </head>
    <body>
      <input id='button' type='button' onclick="prompt('这是一个prompt弹窗');" value='单击此按钮,弹出prompt弹出窗'/></input>
    </body>
  </html>

  Java语言版本API实例 

  @Test
  public void testHandlePrompt() {
    driver.manage().window().maximize();
    driver.get(url);
    WebElement button = driver.findElement(By.xpath("//input"));
    button.click();
    try {
      Alert alert = driver.switchTo().alert();
      Assert.assertEquals("这是一个prompt弹窗", alert.getText());
      //在prompt弹窗上输入内容
      alert.sendKeys("selemiun");
      //点击prompt上的确定按钮
      alert.accept();
      //alert.dismiss(); 取消按钮
    } catch (NoAlertPresentException exception) {
      Assert.fail("未找到prompt窗口");
      exception.printStackTrace();
    }
  }

posted @ 2019-03-06 10:34  心生意动  阅读(80)  评论(0编辑  收藏  举报