iFrame的定位


原文轉自:WebDriver學習筆記(七)iFrame的定位

原文作者:米陽MeYoung

 

iFrame嵌套的頁面非常常見,然而iFrame內的頁面元素我們沒辦法按常規思路去定位,操作。

平時測試如果遇到代碼沒錯,但就是定位不到頁面元素,這時你就應該第一個反應元素是不是嵌套在iFrame內。

如果是,那么我們的思路就是先定位iFrame再定位iFrame內的元素,這個有點類似於頁面層級元素定位。

具體例子:
1.新建2個html 頁面,放於D盤,作為被測試的頁面
main.html
<html>
    <head >
        <title> FrameTest</title >
    </head >
    <body >
        <div id = "id1"> this is a div !</ div>
        <iframe id = "frame"  frameborder="0" scrolling="no" style="left :0; position:absolute;" src = "iframe.html"></ iframe>
    </body >
</html><span style="font-family: Tahoma;">&nbsp;</span>

 

 

iframe.html

<html>
    <head >
        <title> this is a frame!</title >
    </head >
    <body >
        <div id = "div1"> this is a div !</div>
        <label> input:</label >
        <input id = "input1"></ input>
    </body >
</html>

 

2.具體代碼

switchTo(),選取的作用,也就是交與控制權

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class IFrameTest {
    @Test
    public void iFrameTest() throws InterruptedException {
        // 設置chromedriver的路徑,根據你具體存放位置來設置路徑
        System.setProperty("webdriver.chrome.driver", "C:\\holmosconf\\driverServers\\chromedriver.exe");
        // 啟動Chrome瀏覽器
        WebDriver driver = new ChromeDriver();
        // get方式打開測試頁面
        driver.get("C:\\main.html");
        // 選取frame
        driver.switchTo().frame("frame");;
        // 定位iframe里面的文本框
        driver.findElement(By.id("input1")).sendKeys("這是在iframe里面的文本框");
        // 跳出iframe
        driver.switchTo().defaultContent();
        // 為了看效果,等待3S
        Thread.sleep(3000);
        // 結束測試
        driver.quit();
    }
}

 

上面的iFrame定位用的是ID,如果既沒有ID,也沒有Name時,可以類似底下方法定位iframe:

WebElement frame=driver.findElement(By. xpath( "/html/body/div/iframe" ));
driver.switchTo().frame(frame);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM