13.selenium之警告框處理
阿新 • • 發佈:2020-08-27
在 WebDriver中處理JavaScript所生成的alert、confirm以及prompt十分簡單,具體做法是使用switch_to_alert()方法定位到alert/confirm/prompt,然後使用text/accept/dismiss/sendKeys等方法進行操作。
- getText(): 返回 alert/confirm/prompt 中的文字資訊。
- accept(): 接受現有警告框。
- dismiss(): 解散現有警告框。
- sendKeys(keysToSend): 傳送文字至警告框。
- keysToSend: 將文字傳送至警告框。
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class AlertDemo { public static void main(String[] args) throwsInterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.baidu.com"); driver.findElement(By.xpath("//*[@id=\"s-usersetting-top\"]")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"s-user-setting-menu\"]/div/a[1]")).click(); Thread.sleep(2000); //儲存設定 driver.findElement(By.className("prefpanelgo")).click(); Thread.sleep(2000); //接收彈窗 driver.switchTo().alert().accept(); Thread.sleep(2000); driver.quit(); } }