Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Cách thiết lập style display cho phần tử HTML trong test Selenium


Chúng ta có thể thiết lập style display của phần tử HTML bằng Selenium WebDriver. DOM tương tác với các phần tử trên trang nhờ JavaScript. Selenium thực thi lệnh JavaScript thông qua phương thức executeScript.

Một số thao tác như thiết lập style display có thể thực hiện bằng Javascript Executor. Phương thức getElementById dùng để định vị phần tử, sau đó áp dụng style.display trên webelement và thiết lập kiểu hiển thị.

Cú pháp

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

Ví dụ

Triển khai mã.

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://www.tutorialspoint.com/index.htm");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // Javascript executor class với executeScript method
        JavascriptExecutor j = (JavascriptExecutor) driver;
        // Thiết lập display với style.display method
        j.executeScript("document.getElementById('gsc-i-id1').style.display='block';");
        driver.close();
    }
}

Lưu ý: Cách này hữu ích khi phần tử bị ẩn (display: none) và bạn cần hiển thị nó để thao tác trong test tự động hóa.