Alert彈框是一個(gè)很煩人的控件,因?yàn)楫?dāng)前頁面如果彈出了該彈框,你必須要處理它,不然你不能操作頁面的其它元素,下面我列出了alert彈框在多種場景下的處理辦法。
明確知道系統(tǒng)哪個(gè)地方會(huì)彈alert
常規(guī)處理,該方法只是對(duì)彈出的alert彈框進(jìn)行了捕獲和處理
@Test(enabled=false)
publicvoidff1(){
System.setProperty(key,value);
driver=newChromeDriver();
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
Alertalt=driver.switchTo().alert();
alt.accept();
}
捕獲時(shí)增加智能等待,該方法對(duì)彈出的alert彈框進(jìn)行智能等待,避免了NoAlertPresentException異常的拋出
@Test(enabled = false)
public void ff2() {
System.setProperty(key, value);
driver = new ChromeDriver();
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
Alert alert = wait.until(new ExpectedCondition<Alert>() {
@Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
} catch (NullPointerException e) {
/* Ignore */
System.out.println("ff2 nullpoint");
}
}
捕獲和處理alert時(shí)都增加判斷,使用selenium自帶的ExpectedConditions
@Test(enabled = false)
public void ff3() {
System.setProperty(key, value);
driver = new ChromeDriver();
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
boolean flag = false;
Alert alert = null;
try {
new WebDriverWait(driver, 10).until(ExpectedConditions
.alertIsPresent());
alert = driver.switchTo().alert();
flag = true;
// alert.accept();
} catch (NoAlertPresentException NofindAlert) {
// TODO: handle exception
NofindAlert.printStackTrace();
// throw NofindAlert;
}
if (flag) {
alert.accept();
}
}
以上的幾種方法都是自己知道哪個(gè)地方要彈alert,所以在代碼的某處對(duì)alert進(jìn)行捕獲,但是有時(shí)候我們并不知道哪個(gè)地方會(huì)彈alert彈框,這樣會(huì)導(dǎo)致我們沒有進(jìn)行捕獲代碼拋出了
UnexpectedAlertBehaviour異常,下面我們來看下怎么解決這個(gè)問題。
不清楚系統(tǒng)哪個(gè)地方會(huì)彈alert
對(duì)整個(gè)正常代碼進(jìn)行異常捕獲,寫進(jìn)try里,然后catchUnexpectedAlertBehaviour
@Test(enabled = false)
public void ff4() {
System.setProperty(key, value);
driver = new ChromeDriver();
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
try {
System.out.println("ff4正常處理代碼1");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
} catch (UnhandledAlertException e) {
// TODO: handle exception
driver.switchTo().alert().accept();
System.out.println("ff4進(jìn)入U(xiǎn)nhandledAlertException異常");
}
System.out.println("ff4正常處理代碼2");
}