我们可以使用 selenium webdriver 设置 html 元素的样式显示。 dom 在 javascript 的帮助下与页面上的元素进行交互。 selenium 通过 executescript 方法执行 javascript 命令。要执行的命令作为参数传递给该方法。
一些操作(例如设置样式显示)由 javascript executor 执行。 getelementbyid 方法可用于定位元素。然后我们必须在 webelement 上应用 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://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() }}
以上就是如何在selenium测试中设置html元素的样式显示?的详细内容。