java+selenium處理Iframe中的元素
有時候我們定位元素的時候,發現怎麼都定位不了。 這時候你需要查一查你要定位的元素是否在iframe裏面
selenium 進入iframe 的方法
// 進入 id 叫frameA 的 iframe
driver.switchTo().frame("frameA");
// 回到主窗口
driver.switchTo().defaultContent();
簡單例子
main.html
<html>
<head>
<title>FrameTest</title>
</head>
<body>
<div id="id1">this is main page's div!</div>
<input type="text" id="maininput" />
<br/>
<iframe id="frameA" frameborder="0" scrolling="no" style="left:0;position:absolute;" src="frame.html"></iframe>
</body>
</html>
frame.html
<html>
<head>
<title>this is a frame!</title>
</head>
<body>
<div id="div1">this is iframes div,</div>
<input id="iframeinput"></input>
</body>
</html>
selenium 代碼
public static void testIframe(WebDriver driver)
{
driver.get("E:\\StashFolder\\[email protected]\\Stash\\Tank-MoneyProject\\浦東軟件園培訓中心\\我的教材\\Selenium Webdriver\\frame\\main.html");
// 在 主窗口的時候
driver.findElement(By.id("maininput")).sendKeys("main input");
// 此時 沒有進入到iframe, 以下語句會報錯
//driver.findElement(By.id("iframeinput")).sendKeys("iframe input");
driver.switchTo().frame("frameA");
driver.findElement(By.id("iframeinput")).sendKeys("iframe input");
// 此時沒有在主窗口,下面語句會報錯
//driver.findElement(By.id("maininput")).sendKeys("main input");
// 回到主窗口
driver.switchTo().defaultContent();
driver.findElement(By.id("maininput")).sendKeys("main input");
}