java selenium 處理Iframe 中的元素
有時候我們定位元素的時候,發現怎么都定位不了。 這時候你需要查一查你要定位的元素是否在iframe里面
閱讀目錄
什么是iframe
iframe 就是HTML 中,用于網頁嵌套網頁的。 一個網頁可以嵌套到另一個網頁中,可以嵌套很多層。
selenium 中提供了進入iframe 的方法
1
2
3
4
5
6
|
// 進入 id 叫frameA 的 iframe dr.switchTo().frame( "frameA" ); // 回到主窗口 dr.switchTo().defaultContent(); |
main.html
1
2
3
4
5
6
7
8
9
10
11
|
< 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
1
2
3
4
5
6
7
8
9
|
< 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 代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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" ); } |
以上就是java selenium處理Iframe中的元素的示例,后續繼續整理相關資料,謝謝大家對本站的支持!