import java.util.Set; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.ie.InternetExplorerDriver; public class AlertOperate { static WebDriver dr = new InternetExplorerDriver(); public static void main(String args[]) throws InterruptedException{ dr.get("www.baidu.com"); dr.findElement(By.id("lb")).click(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } tanchukuang(); } //处理潜在的1个alert(javascript弹出框) public boolean dealPotentialAlert(WebDriver driver,boolean option) { boolean flag = false; try { Alert alert = driver.switchTo().alert(); if (null == alert) throw new NoAlertPresentException(); try { if (option) { alert.accept(); System.out.println("Accept the alert: " + alert.getText()); } else { alert.dismiss(); System.out.println("Dismiss the alert: " + alert.getText()); } flag = true; } catch (WebDriverException ex) { if (ex.getMessage().startsWith("Could not find")) System.out.println("There is no alert appear!"); else throw ex; } } catch (NoAlertPresentException e) { System.out.println("There is no alert appear!"); } return flag; } //处理非JS弹窗 public static boolean testNewWindow(){ //当前窗口句柄 String currentHandle = dr.getWindowHandle(); //得到所有窗口的句柄 Set<String> handles = dr.getWindowHandles(); handles.remove(currentHandle); if (handles.size() > 0) { try{ dr.switchTo().window(handles.iterator().next()); //dr.switchTo().window(dr.getWindowHandles().iterator().next()); return true; }catch(Exception e){ System.out.println(e.getMessage()); return false; } } System.out.println("Did not find window"); return false; } //一般弹出窗口 public static void tanchukuang() throws InterruptedException{ //得到所有窗口 Set<String> allWindowsId = dr.getWindowHandles(); //通过查找页面内容得到新的窗口 for(String windowId : allWindowsId){ dr.switchTo().window(windowId); Thread.sleep(1000); dr.findElement(By.id("TANGRAM__PSP_10__userName")).sendKeys("test"); //第一个按钮是确定按钮 //dr.findElement(By.xpath("//button[@type='button']")).click(); //System.out.println(dr.switchTo().window(windowId).getTitle()); break; } } } |