章节十四、8-javaScript弹框处理
一、javaScript弹框没有id、也没有xpath,在F12开发者选项中无法直接通过鼠标去选择弹窗来确定元素在代码中的位置。
弹窗有两种,一种实只有“确定”按钮的alert类型的弹窗:
另一种是带有“确定”和“取消”按钮的弹窗:
二、如何在代码中找到javaScript弹窗的位置?
1、首先我们需要定位出能够调出来弹窗的HTML的按钮:
2、在对应的标签中我们可以看到,它们的属性中都带有一个onclick带有函数值,例如alert按钮对应的函数值为“displayAlert()”,confirmbtn对应的函数值为“displayConfirm()”。
3、通过对应的函数值去javaScript标签中查找对应的代码。
通过下面的图片我们可以看到“displayAlert()”函数调用的是javascript中的alert功能,“displayAlert()”函数调用的是javascript中的confirmbtn功能。
三、案例演示
1 package switchto; 2 3 import java.util.concurrent.TimeUnit; 4 5 import org.junit.jupiter.api.AfterEach; 6 import org.junit.jupiter.api.BeforeEach; 7 import org.junit.jupiter.api.Test; 8 import org.openqa.selenium.Alert; 9 import org.openqa.selenium.By; 10 import org.openqa.selenium.WebDriver; 11 import org.openqa.selenium.chrome.ChromeDriver; 12 13 class SwitchAlert { 14 15 WebDriver driver; 16 String url; 17 18 @BeforeEach 19 void setUp() throws Exception { 20 driver = new ChromeDriver(); 21 url = "file:///C:/Users/acer/Desktop/%E5%85%B6%E5%AE%83/PracticePage.html"; 22 driver.manage().window().maximize(); 23 driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS); 24 driver.get(url); 25 } 26 27 @Test 28 void test1() throws InterruptedException { 29 driver.findElement(By.id("alertbtn")).click(); 30 Thread.sleep(2000); 31 // 这个方法可以返回一个alert对象 32 Alert alert = driver.switchTo().alert(); 33 // 表示操作JavaScript弹窗的“确定”按钮 34 alert.accept(); 35 // 表示操作JavaScript弹窗的“取消”按钮,案例中alert没有取消键,所以此处进行注释 36 // alert.dismiss(); 37 } 38 39 @Test 40 void test2() throws InterruptedException { 41 driver.findElement(By.id("confirmbtn")).click(); 42 Thread.sleep(2000); 43 // 这个方法可以返回一个alert对象 44 Alert confirmbtn = driver.switchTo().alert(); 45 // 表示操作JavaScript弹窗的“确定”按钮 46 // confirmbtn.accept(); 47 // 表示操作JavaScript弹窗的“取消”按钮 48 confirmbtn.dismiss(); 49 } 50 51 @AfterEach 52 void tearDown() throws Exception { 53 Thread.sleep(2000); 54 driver.quit(); 55 } 56 }
如果有不明白的小伙伴可以加群“555191854”问我,群里都是软件行业的小伙伴相互一起学习。
内容具有连惯性,未标注的地方可以看前面的博客,这是一整套关于ava+selenium自动化的内容,从java基础开始。
欢迎关注,转载请注明来源。