Nội dung bài học
Alert (thông báo) trong Selenium là gì?
Một Alert trong Selenium là một hộp thông báo nhỏ xuất hiện trên màn hình để cung cấp cho người dùng một số thông tin hoặc thông báo. Nó thông báo cho người dùng một số thông tin hoặc lỗi cụ thể, yêu cầu quyền để thực hiện các tác vụ nhất định và nó cũng cung cấp các thông báo cảnh báo.
Dưới đây là một số loại cảnh báo:
1) Cảnh báo đơn giản
Lớp cảnh báo đơn giản trong Selenium hiển thị một số thông tin hoặc cảnh báo trên màn hình.
2) Cảnh báo nhắc nhở.
Thông báo nhắc nhở này yêu cầu một số đầu vào từ người dùng và trình duyệt web Selenium có thể nhập văn bản bằng cách sử dụng các phím gửi ("đầu vào….").
3) Cảnh báo xác nhận.
Cảnh báo xác nhận này yêu cầu quyền để thực hiện một số loại hoạt động.
Cách xử lý Alert trong Selenium Java
Chèn thư viện cái:
import org.openqa.selenium.Alert;
Các hàm xử lý:
1) void dismiss() // To click on the 'Cancel' button of the alert.
driver.switchTo().alert().dismiss();
2) void accept() // To click on the 'OK' button of the alert.
driver.switchTo().alert().accept();
3) String getText() // To get message Text.
driver.switchTo().alert().getText();
4) void sendKeys(String stringToSend) // To input data on inputtext to alert box.
driver.switchTo().alert().sendKeys("Text");
Bắt đầu nào
Step 1) Launch the web browser and open the site "http://demo.guru99.com/test/delete_customer.php "
Step 2) Enter Any Customer id.
Step 3) After entering the customer ID, Click on the "Submit" button.
Step 4) Accept/Dismiss the alert.
Hoặc dạng này
Chạy code thực hành luôn cho nóng:
package anhtester.com.bai13_alertpopupiframe;
import anhtester.com.SetupBrowser;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class TestAlert extends SetupBrowser {
@Test
public void TestAlert01() throws InterruptedException {
driver.get("http://demo.guru99.com/test/delete_customer.php");
driver.findElement(By.name("cusid")).sendKeys("53920");
driver.findElement(By.name("submit")).submit();
// Khai báo chuyển hướng đến Alert với đối tượng
Alert alert = driver.switchTo().alert();
// Get message trên alert
String alertMessage = driver.switchTo().alert().getText();
// Displaying alert message
System.out.println(alertMessage);
Thread.sleep(2000);
// accept() = nhấn Ok button
// driver.switchTo().alert().accept(); //Cách 1
alert.accept(); //Cách 2
//Nhấn Cancel button
//alert.dismiss();
Thread.sleep(2000);
}
}
Ví dụ sendKeys:
package anhtester.com.bai13_alertpopupiframe;
import anhtester.com.SetupBrowser;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class TestAlert extends SetupBrowser {
@Test
public void TestAlert02() throws InterruptedException {
driver.get("http://demo.automationtesting.in/Alerts.html");
Thread.sleep(2000);
driver.findElement(By.xpath("//a[normalize-space()='Alert with Textbox']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//button[normalize-space()='click the button to demonstrate the prompt box']")).click();
//button[normalize-space()='click the button to demonstrate the prompt box']
//Nhấn sendKeys vào ô text
driver.switchTo().alert().sendKeys("Anh Tester");
Thread.sleep(2000);
driver.switchTo().alert().accept();
Thread.sleep(2000);
}
}
Ví dụ sendKey khác:
@Test
public void TestAlert03() throws InterruptedException {
driver.get("https://demoqa.com/alerts");
Thread.sleep(1000);
driver.findElement(By.xpath("//button[@id='promtButton']")).click();
Thread.sleep(500);
//Nhấn sendKeys vào ô text
driver.switchTo().alert().sendKeys("Anh Tester");
Thread.sleep(500);
//Nhấn Ok button
driver.switchTo().alert().accept();
Thread.sleep(1000);
//Kiểm tra giá trị sendKeys
String value = driver.findElement(By.xpath("//span[@id='promptResult']")).getText();
System.out.println(value);
Assert.assertTrue(value.contains("Anh Tester"), "Không chứa Text sendKeys");
Thread.sleep(2000);
}
Cách xử lý Pop-up window trong Selenium Java
Pop-up window là cái gì??
![[Selenium Java] Lesson 13: Cách xử lý Alert, Popup Window và iFrame | Anh Tester](/uploads/lesson/selenium_java/alert-popup-iframe/new_tab.jpg)
![[Selenium Java] Lesson 13: Cách xử lý Alert, Popup Window và iFrame | Anh Tester](/uploads/lesson/selenium_java/alert-popup-iframe/popup_window.jpg)
Thực hành thao tác nào:
Step 1) Launch the site.
Mở trang web demo: http://demo.guru99.com/popup.php
Step 2) Click on link "Click Here ".
Click vào link "Click Here" thì nó sẽ mở một Tab window mới.
Step 3) New Child Window opens.
Tab mới được mở và nó chứa thông tin nhập email
Step 4) Enter your email ID and submit.
Step 5) Display the Access Credentials on submitting the page.
Tab window sau khi submit sẽ chứa thông tin Detail
- Đóng tab con này đi
- Chuyển về tab window chính (parent window).

Cú pháp xử lý Windown Popup:
- get.windowhandle (): Phương thức này giúp lấy cửa sổ điều khiển của cửa sổ hiện tại
- get.windowhandles (): Phương thức này giúp lấy các xử lý của tất cả các cửa sổ đã mở
- set: Phương thức này giúp thiết lập các chốt cửa sổ dưới dạng một chuỗi. set <string> set = driver.get.windowhandles ()
- switchTo: Phương pháp này giúp chuyển đổi giữa các cửa sổ
- action: Phương pháp này giúp thực hiện các hành động nhất định trên cửa sổ
(getTitle, getCurrentUrl, get,...)
Đây là một số phương pháp sẽ được sử dụng để xử lý nhiều cửa sổ trong Selenium.
Với ví dụ từ mô tả trên trang Guru99:
Code bình thường chưa chuyển sang Window mới:
package anhtester.com.bai13_alertpopupiframe;
import anhtester.com.SetupBrowser;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import java.util.Set;
public class TestPopup extends SetupBrowser {
@Test
public void TestPopup01() throws InterruptedException {
driver.get("http://demo.guru99.com/popup.php");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();
Thread.sleep(1000);
driver.findElement(By.name("emailid")).sendKeys("abc@gmail.com");
driver.findElement(By.name("btnLogin")).click();
Thread.sleep(2000);
}
}
Nó sẽ báo là không tìm thấy Element email input =))
Code chuyển sang tab Window mới:
package anhtester.com.bai13_alertpopupiframe;
import anhtester.com.SetupBrowser;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import java.util.Set;
public class TestPopup extends SetupBrowser {
@Test
public void TestPopup02() throws InterruptedException {
driver.get("http://demo.guru99.com/popup.php");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();
// Lưu lại lớp window đầu tiên - mã ID hơi dài, in ra sẽ thấy :)
String MainWindow = driver.getWindowHandle();
System.out.println(MainWindow);
// Get all new opened tab Window.
Set<String> windows = driver.getWindowHandles();
//Set là một Collection để lưu các phần tử giá trị KHÔNG trùng lặp.
//Cách duyệt từng phần tử không trùng lặp trong Collection (Set) - Java Basic
for (String window : windows) {
System.out.println(window);
if (!MainWindow.equals(window)) {
//So sánh nếu thằng nào khác thằng Chính (đầu tiên) thì chuyển hướng qua nó mới thao tác được
//Switch to Child window
driver.switchTo().window(window);
Thread.sleep(2000);
System.out.println("Đã chuyển đến lớp Window con");
//Một số hàm hỗ trợ
System.out.println(driver.switchTo().window(window).getTitle());
System.out.println(driver.switchTo().window(window).getCurrentUrl());
driver.findElement(By.name("emailid")).sendKeys("abc@gmail.com");
driver.findElement(By.name("btnLogin")).click();
Thread.sleep(1000);
//Get text trang sau khi Submit
System.out.println(driver.findElement(By.xpath("//table//td//h2")).getText());
// Closing the Child Window.
Thread.sleep(2000);
driver.close();
}
}
// Switching to Parent window (Main Window)
driver.switchTo().window(MainWindow);
System.out.println("Đã chuyển về lớp Window chính: " + driver.getCurrentUrl());
Thread.sleep(2000);
}
}
Nói thêm về Set chút
Ví dụ có: Set<String> setA = driver.getWindowHandles();
Duyệt Set với bộ lặp Iterator:
Iterator<String> iterator = setA.iterator();
while (iterator.hasNext()) {
System.out.println((String) iterator.next());
}
Duyệt Set với vòng lặp for-each:
for (String element : setA) {
System.out.println(element);
}
Cách xử lý iFrames trong Selenium Java
iFrame là gì?
iFrame là một trang web hoặc một khung nội tuyến được nhúng trong một trang web khác hoặc một tài liệu HTML được nhúng bên trong một tài liệu HTML khác. Khung nội tuyến thường được sử dụng để thêm nội dung từ các nguồn khác như quảng cáo vào một trang web.
Khung nội tuyến được xác định bằng thẻ <
iframe>
Cách xác định iframe trên trang
Nếu dùng Chrome thì right click vào cái Messenger trang Anh Tester menu Contact sẽ thấy như hình
Hoặc dạng quảng cáo chèn vào các trang báo
Chúng ta có thể xác định tổng số iframe bằng cách sử dụng đoạn mã sau:
int sizeIFrame = driver.findElements(By.tagName("iframe")).Size();
Cách chuyển đến iFrame cụ thể
Chuyển sang khung theo Chỉ mục (thứ tự):
Giả sử nếu có 100 khung trong trang, chúng ta có thể chuyển sang khung trong Selenium bằng cách sử dụng chỉ mục.
driver.switchTo().frame(0);
driver.switchTo().frame(1);
Chuyển sang khung theo Tên hoặc ID:
Tên và ID là các thuộc tính để xử lý các khung trong Selenium mà qua đó chúng ta có thể chuyển sang iframe.
driver.switchTo().frame("iframe1");
driver.switchTo().frame("id của phần tử");
Chiến nào code code code
package anhtester.com.bai13_alertpopupiframe;
import anhtester.com.SetupBrowser;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
public class TestIFrame extends SetupBrowser {
@Test
public void iFrame01() throws InterruptedException {
driver.navigate().to("https://anhtester.com/contact");
Thread.sleep(3000);
System.out.println("iframe total: " + driver.findElements(By.tagName("iframe")).size());
Thread.sleep(1000);
//----Switch to content of Messenger--------
driver.switchTo().frame(0);
System.out.println(driver.findElement(By.tagName("strong")).getText());
//----Switch to icon of Messenger---------
//1. Switch to Parent WindowHandle
driver.switchTo().parentFrame();
//2. Switch to iframe icon of Messenger
driver.switchTo().frame(1);
driver.findElement(By.tagName("svg")).click(); //Nhấn icon để ẩn messenger chat đi
Thread.sleep(2000);
}
}
Anh Tester
facebook.com/anhtester
Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu