เราสามารถทำงานกับ iframe ใน Selenium webdriver เฟรมถูกกำหนดด้วยแท็ก

โดยค่าเริ่มต้นซีลีเนียมจะสามารถเข้าถึงไดรเวอร์เบราว์เซอร์หลักได้ ในการเข้าถึงองค์ประกอบเฟรม โฟกัสของไดรเวอร์ต้องเปลี่ยนจากหน้าต่างเบราว์เซอร์หลักเป็นเฟรม มีหลายวิธีในการเปลี่ยนไปใช้เฟรม -
-
switchTo().frame(id) - รหัสหรือชื่อของเฟรมถูกส่งผ่านเป็นอาร์กิวเมนต์
ไวยากรณ์ −driver.switchTo().frame("id") เปลี่ยนเป็นเฟรมที่มี id
-
switchTo().frame(m) - ดัชนีของเฟรมถูกส่งผ่านเป็นอาร์กิวเมนต์ ดัชนีเริ่มต้นจากศูนย์
ไวยากรณ์ −driver.switchTo().frame(0) เปลี่ยนเป็นเฟรมแรกในหน้า
-
switchTo().frame(webelement n) - Webelement ของเฟรมถูกส่งผ่านเป็นอาร์กิวเมนต์
ไวยากรณ์ −driver.switchTo().frame(l) เปลี่ยนเป็นเฟรมด้วย webelement l.
-
switchTo().defaultContent() – การสลับโฟกัสจากเฟรมไปยังหน้าหลัก
ไวยากรณ์ −driver.switchTo().defaultContent()
ตัวอย่าง
การติดตั้งโค้ด
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:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://the-internet.herokuapp.com/frames");
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
// identify element and click
driver.findElement(By.partialLinkText("Nested")).click();
// switching to frame with frame name
driver.switchTo().frame("frame-bottom");
WebElement m = driver.findElement(By.cssSelector("body"));
System.out.println("Frame text: " +m.getText());
driver.close();
}
} ผลลัพธ์
