如何在 Selenium 測試中設定 html 元素的樣式顯示?


我們可以使用 Selenium 網頁驅動程式設定 html 元素的樣式顯示。DOM 藉助 JavaScript 與頁面上的元素進行互動。Selenium 透過使用 **executeScript** 方法來執行 JavaScript 命令。需要執行的命令作為引數傳遞給方法。

設定樣式顯示等一些操作都可由 **Javascript Executor** 執行。**getElementById** 方法可用於定位元素。然後我們必須對 Web 元素應用 **style.display** 方法並設定顯示型別。

語法

executor.executeScript
("document.getElementById('gsc-i-id1').style.display='block';");

示例

程式碼實現。

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 ElementStyleSet{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // set the display with style.display method
      j.executeScript ("document.getElementById('gsc-i-id1').style.display='block';");
      driver.close()
   }
}

更新於: 2020 年 10 月 26 日

已檢視 2K+ 次

開始你的 事業

完成課程認證

開始
廣告
© . All rights reserved.