java - 如何使用 Selenium Webdriver 和 Java 提取元素的显示属性

标签 java selenium selenium-webdriver display getattribute

无法定位div中的隐藏元素

<div id="divDuplicateBarcodeCheck" class="spreadsheetEditGui" style="z- 

 index: 1200; width: 640px; height: 420px; top: 496.5px; left: 640px; 

display:block"> ==$0

我想定位显示元素,但该元素是隐藏的,我也为其编写了代码。

String abc=d.findElement(By.xpath("//div[@id='divDuplicateBarcodeCheck']/"))
.getAttribute("display");
 System.out.println(abc);
 Thread.sleep(3000);
 if(abc.equalsIgnoreCase("block"))      
 {          
 d.findElement(By.id("duplicateBarcodeCheck")).click();   
System.out.println("duplicate barcode Close");                                              
}
else    
{    System.out.println("Barcode selected");}

最佳答案

没有display这样的属性。它是 style 属性的一部分。

您可以找到该元素并获取其属性样式:

String style = d.findElement(By.xpath("//div[@id='divDuplicateBarcodeCheck']")).getAttribute("style");
if(style.contains("block")) {          
    d.findElement(By.id("duplicateBarcodeCheck")).click();   
    System.out.println("duplicate barcode Close");                                              
} else {   
    System.out.println("Barcode selected");}
}

或者您可以直接使用 cssSelector 找到此元素(也可以使用 xpath):

WebElement abc = d.findElement(By.cssSelector("div[id='divDuplicateBarcodeCheck'][style*='display: block']"))

请注意,如果未找到该元素,上面的代码将抛出 NoSuchElementException 。您可以使用 try-catch block 执行类似的操作,就像在 if-else 语句中执行的操作一样,如下所示:

try {
    d.findElement(By.cssSelector("div[id='divDuplicateBarcodeCheck'][style*='display: block']"));
    d.findElement(By.id("duplicateBarcodeCheck")).click();
    System.out.println("duplicate barcode Close");  
} catch (NoSuchElementException e) {
     System.out.println("Barcode selected");
}

关于java - 如何使用 Selenium Webdriver 和 Java 提取元素的显示属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55114422/

相关文章:

Java从字符串中获取数字或货币格式

ruby - Selenium Ruby 报告

java - 如何使用 Selenium Webdriver 和 Java 从包含在多个 span 标签内的 span 元素中获取实际文本

javascript - Selenium 没有注册按钮按下

javascript - 如何在 webdriverio 中使用 socks 认证

Python:命令行参数的传递方式与硬编码行不同

java - 弱引用 get() 方法的安全性如何? (安卓,异步任务)

java - 将两个表连接到一个列表中

java - Selenium Firefox Webdriver NoSuchElement 链接异常 :

java - 在 Jersey Client 2 中编码大括号