如何在 Selenium WebDriver 中从框架返回当前页面?
seleniumautomation testingtesting tools
我们可以使用 Selenium WebDriver 从框架返回当前页面。框架在 HTML 代码中使用 iframe、frame 或 frameset 标签定义。框架用于将一个 HTML 文档嵌入到另一个 HTML 文档中。

Selenium 默认访问主浏览器驱动程序。要访问框架元素,驱动程序的焦点必须从主浏览器窗口切换到该框架。要再次从框架返回当前页面,可以使用 `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);
// 识别元素并点击
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.switchTo().defaultContent();
driver.close();
}
}
输出


