如何从硒网驱动中的框架返回当前页面?


借助硒网驱动,我们可以从框架返回当前页面。框架使用 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();
   }
}

输出

更新时间: 2020-10-26

2 千次以上浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.