Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

การทำงานกับ Iframe ใน Selenium WebDriver

Iframe (Inline Frame) ใช้สำหรับฝังเอกสาร HTML อื่นภายในหน้าเว็บหลัก Selenium ต้องสลับบริบท (context) จากหน้าหลักไปยัง iframe ก่อนจึงจะเข้าถึงองค์ประกอบภายในได้

วิธีการสลับไปยัง Iframe

เมธอด คำอธิบาย ตัวอย่าง
switchTo().frame(id) ใช้ id หรือ name ของ iframe driver.switchTo().frame("frameName")
switchTo().frame(index) ใช้ลำดับของ iframe (เริ่มจาก 0) driver.switchTo().frame(0)
switchTo().frame(webElement) ใช้ WebElement ของ iframe driver.switchTo().frame(element)
switchTo().defaultContent() กลับไปหน้าหลัก (ออกจาก iframe) driver.switchTo().defaultContent()

ตัวอย่างโค้ด Java สมบูรณ์

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class iFrameMethods {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://the-internet.herokuapp.com/frames");
        driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);

        // คลิกลิงก์ไปยังหน้า Nested Frames
        driver.findElement(By.partialLinkText("Nested")).click();

        // สลับไปยัง iframe ด้วย name
        driver.switchTo().frame("frame-bottom");

        // ค้นหาองค์ประกอบภายใน iframe
        WebElement body = driver.findElement(By.cssSelector("body"));
        System.out.println("Frame text: " + body.getText());

        // กลับไปหน้าหลัก
        driver.switchTo().defaultContent();

        driver.close();
    }
}

ขั้นตอนสำคัญ

  1. หา iframe ก่อน (ด้วย id, name, index, หรือ WebElement)
  2. ใช้ switchTo().frame() เข้าสู่บริบทของ iframe
  3. ทำงานกับองค์ประกอบภายใน iframe ได้ตามปกติ
  4. ใช้ switchTo().defaultContent() กลับมาหน้าหลักเมื่อเสร็จสิ้น

กรณี Iframe ซ้อนกัน (Nested Iframes)

ต้องสลับทีละชั้น: เข้า iframe ชนอกก่อน แล้วค่อยเข้า iframe ชั้นใน และใช้ switchTo().parentFrame() เพื่อย้อนกลับทีละชั้น