如何使用 Selenium 在框架中執行 JavaScript?


我們可以透過 executeScript 方法在框架中使用 Selenium 中的 Javascript。要執行的命令被作為方法引數傳入。

接下來,我們使用 return 關鍵字返回 Selenium 命令的值。我們必須藉助 Javascript 中的 window.length 命令來計算頁面中的框架數量。

語法

JavascriptExecutor j = (JavascriptExecutor) driver;
int i = Integer.parseInt(j.executeScript("return window.length").toString());

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class FramesJS{
   public static void main(String[] args) {
         System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("http://www.uitestpractice.com/Students/Switchto");
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // Javascript executor to return value frame count
      JavascriptExecutor j = (JavascriptExecutor) driver;
      int i = Integer.parseInt
      (j.executeScript("return window.length").toString());
      System.out.print("Frame count is: " +i);
      // switching to the frame and get text within frame
      driver.switchTo().frame("iframe_a");
      WebElement l = driver.findElement(By.cssSelector("h1"));
      System.out.print("Text within frame: " + l.getText());
      driver.quit();
   }
}

輸出

更新於: 28/11/2020

638 次瀏覽

開啟你的 職業

完成課程後即可獲得認證

開始學習
廣告
© . All rights reserved.