6.7 Selenium操作iframe中的元素

    技术2022-07-10  148

    1.简介 当元素无法定位时,需要检查定位的元素是否在iframe里面。iframe是HTML中用于网页嵌套的,一个网页可以嵌套到另一个网页中,并且可以嵌套多层。

    2.案例 程序6-20演示效果:打开含有iframe的网页,在主窗口的输入框中输入“main input”,停留2秒后,切换到iframe中,在输入框中输入“iFrame input”,再次停留2秒后,回到主窗口,并在输入框中输入“main input again”。包含iframe的HTML代码如下所示。

    //main.html <html> <head> <title>FrameTest</title> </head> <body> <div>this is main page's div!</div> <input type="text" id="mainInput" /> <br/> <iframe id="frame" frameborder="0" scrolling="no" style="left:0;position:absolute;" src="frame.html"></iframe> </body> </html> //iframe.html <html> <head> <title>this is a frame!</title> </head> <body> <div>this is iframes div,</div> <input id="iFrameInput"></input> </body> </html> public class IFrame { public static void main(String[] args) throws InterruptedException { WebDriver driver = WebDriverUtils.getWebDriver(); String url = "https://www.leichuangkj.com/main.html"; driver.get(url); //在主窗口的时候 driver.findElement(By.id("mainInput")).sendKeys("main input"); Thread.sleep(2000); //frame窗口 driver.switchTo().frame("frame"); driver.findElement(By.id("iFrameInput")).sendKeys("iFrame input"); Thread.sleep(2000); //回到主窗口 driver.switchTo().defaultContent(); driver.findElement(By.id("mainInput")).clear(); driver.findElement(By.id("mainInput")).sendKeys("main input again"); Thread.sleep(2000); driver.quit(); } }
    Processed: 0.012, SQL: 12