今天主要接触了 switchTo 方法,使用这个方法,就可以直接切换到 iframe 窗口内,切换后使用js 时就可以把 iframe 当做当前的主窗口来使用了
package lesson5;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;public class ExampleForIframe2 { static WebDriver driver; @BeforeClass public static void init() { System.out.println("init..."); // 如果你的 FireFox 没有安装在默认目录,那么必须在程序中设置 System.setProperty("webdriver.firefox.bin", "D://Program Files//Mozilla Firefox//firefox.exe"); // 创建一个 FireFox 的浏览器实例 driver = new FirefoxDriver(); } @Test public void test() { // 让浏览器访问 zTree Demo driver.get("http://www.ztree.me/v3/demo.php#_102"); // 等待 iframe 加载完毕,Timeout 设置10秒 try { (new WebDriverWait(driver, 10, 500)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { Boolean loaded = (Boolean) ((JavascriptExecutor)driver).executeScript("return !!demoIframe.$.fn.zTree.getZTreeObj('treeDemo');"); return loaded; } }); } catch(Exception e) { e.printStackTrace(); } driver.switchTo().frame("demoIframe"); ((JavascriptExecutor)driver).executeScript("window.zTreeObj = $.fn.zTree.getZTreeObj('treeDemo');"); //利用 expandNode 方法展开第2个根节点 ((JavascriptExecutor)driver).executeScript("window.zTreeNode = window.zTreeObj.getNodes()[1]; window.zTreeObj.expandNode(window.zTreeNode, true);"); // 等待 5 秒 try { (new WebDriverWait(driver, 5, 1000)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return false; } }); } catch(Exception e) {} } @AfterClass public static void destory() { System.out.println("destory..."); //关闭浏览器 driver.quit(); }}新闻热点
疑难解答