在 WebDriver中处理JavaScript所生成的alert、confirm以及prompt十分简单,具体做法是使用switch_to_alert()方法定位到alert/confirm/prompt,然后使用text/accept/dismiss/sendKeys等方法进行操作。
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) throws InterruptedException { 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(); } }
原文:https://www.cnblogs.com/peiminer/p/13571031.html