เราสามารถตั้งค่าการแสดงสไตล์ขององค์ประกอบ html ด้วย Selenium webdriver DOM โต้ตอบกับองค์ประกอบบนหน้าด้วยความช่วยเหลือของ Javascript ซีลีเนียมรันคำสั่งจาวาสคริปต์โดยใช้ executeScript กระบวนการ. คำสั่งที่จะดำเนินการจะถูกส่งต่อเป็นอาร์กิวเมนต์ของเมธอด
การดำเนินการบางอย่างเช่นการตั้งค่าการแสดงรูปแบบจะดำเนินการโดย Javascript Executor . getElementById สามารถใช้วิธีการเพื่อค้นหาองค์ประกอบ จากนั้นเราก็ต้องใช้ style.display วิธีการบน webelement และตั้งค่าประเภทการแสดงผล
ไวยากรณ์
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://www.tutorialspoint.com/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()
}
}