如何從硒網驅動中的框架返回當前頁面?
藉助硒網驅動,我們可以從框架返回當前頁面。框架使用 html 程式碼中的 <iframe>、<frame> 或 <frameset> 標記定義。框架用於在另一個 HTML 文件中嵌入一個 HTML 文件。
預設情況下,硒可以訪問主瀏覽器驅動。為了訪問框架元素,必須將驅動程式的焦點從主瀏覽器視窗切換到框架。要從框架重新聚焦到當前頁面,需要使用 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 SwitchBackFrame{ 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(4, 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()); // switch from frame to main page driver.switchTo().defaultContent(); driver.close(); } }
輸出
廣告