有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Webdriver Selenium获取“style”元素的值

我想检查样式元素的值是否大于某个特定值(即,是否左>;666px?),但我无法获得价值

下面是我想要捕获的样式的HTML代码:

<pre><span id="da2c" style="left: 666px; top: 27px;"></pre>

我正在使用此代码尝试打印其值,但它没有打印:

System.out.print(driver.findElement(By.id("da1c")).findElement(By.cssSelector("span")).getAttribute("style"));

我想要这样的东西:

if ((driver.findElement(By.id("da1c")).findElement(By.cssSelector("span")).getAttribute("style")).value> 700) {
  System.out.println("value exceeding")
}

共 (3) 个答案

  1. # 1 楼答案

    您可以捕获计算出的Css值,如下面的firebug屏幕截图所示:

    enter image description here

    像这样:

    WebDriver web = new FirefoxDriver(;
    String visibility = web.findElement(By.xpath("//your xpath")).getCssValue("display");
    
  2. # 2 楼答案

    如果在该跨度上执行.getAttribute("style"),将收到一个字符串

    left: 666px; top: 27px;
    可以使用字符串操纵来获取特定样式

    或者,您可以使用JavaScriptExecutor执行一些javascript魔术,并通过

    String script = "var thing = window.document.getElementById('da2c'); 
                                 window.document.defaultView.getComputedStyle(thing, null).getPropertyValue('left');";
    

    然后从那里检查

  3. # 3 楼答案

    driver.findElement(By.locator( yourLocator )).getAttribute( requiredAttribute )
    

    它将返回字符串