简体   繁体   English

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

[英]How to extract the display attribute of an element using Selenium Webdriver and Java

unable to locate the hidden element in div 无法在div中找到隐藏的元素

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

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

display:block"> ==$0

I want to locate the display element, but the element is hidden, i have written the code for it too. 我想找到显示元素,但是该元素是隐藏的,我也为此编写了代码。

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");}

There is no such attribute as display . 没有诸如display这样的属性。 It's part of style attribute. 它是style属性的一部分。

You can either find the element and get its attribute 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");}
}

OR you can find this element directly with cssSelector (it's also possible with xpath): 或者,您可以直接使用cssSelector找到该元素(也可以使用xpath找到):

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

Note, that above will throw NoSuchElementException if the element was not found. 请注意,如果找不到该元素,则以上内容将引发NoSuchElementException You can use try-catch block to perform similar operations just like you did in if-else statement like this: 您可以使用try-catch块执行类似的操作,就像在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");
}

If I'm getting you correct you are trying to archive checking if an element is displayed or not. 如果您正确无误,则尝试存档检查是否显示元素。 You could do something like this using plain selenium and java: 您可以使用纯硒和java来执行以下操作:

// the @FindBy annotation provides a lazy implementation of `findElement()` 
@FindBy(css = "#divDuplicateBarcodeCheck")
private WebElement barcode;

@Test
public void example() {
    driver.get("http://some.url");
    waitForElement(barcode);
    // isDisplay() is natively provided by type WebElement
    if (barcode.isDisplayed()) {
        // do something
    } else {
        // do something else
    }
}

private void waitForElement(final WebElement element) {
    final WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.visibilityOf(element));
}

Your Test (an end-to-end UI test!) should not stick to an implementation detail like display:none or display:block . 您的测试(端到端UI测试!)不应遵循display:nonedisplay:block类的实现细节。 Imagine the implementation will be changed to remove the element via javascript or something. 想象一下实现将被更改为通过javascript或其他方式删除元素。 A good selenium test should always try represent a real users perspective as good as possible. 良好的硒测试应始终尝试尽可能代表真实的用户观点。 Means if the UI will still behave the same your test should still be successful. 表示如果UI仍然具有相同的行为,则您的测试仍应成功。 Therefore you should do a more general check - is an element displayed or not. 因此,您应该进行更一般的检查-是否显示元素。

This is one of the basic functionalities of Seleniums WebElement interface , or to be even more precise its isDisplayed() method. 这是Seleniums WebElement接口的基本功能之一,或更确切地说,它是isDisplayed()方法。

Quote from the Selenium Java Docs : 引用Selenium Java Docs

boolean isDisplayed() boolean isDisplayed()

Is this element displayed or not? 是否显示此元素? This method avoids the problem of having to parse an element's "style" attribute. 此方法避免了必须解析元素的“样式”属性的问题。 Returns: Whether or not the element is displayed 返回:是否显示元素

Furthermore I would recommend to write some small helper methods for things like that, in my experience it's a common use case you'll face more often. 此外,我建议为此类事情编写一些小的辅助方法,以我的经验,这是您会经常遇到的常见用例。 helper method could for instance look something like this: 例如,辅助方法可能看起来像这样:

boolean isElementVisible(final By by) {
    return driver.findElement(by).isDisplayed();
}

boolean isElementVisible(final WebElement element) {
    return element.isDisplayed();
}

If you are using some Selenium abstractions like FluentLenium or Selenide things will become even more convenient because they provide things like assertion extensions and custom matchers for well known assertion libraries like assertJ, hamcrest, junit. 如果您使用诸如FluentLeniumSelenide之类的Selenium抽象,则它们将变得更加方便,因为它们为诸如assertJ,hamcrest,junit之类的知名断言库提供断言扩展和自定义匹配器之类的东西。

For instance with FluentLenium and AssertJ (a stack that i can personally recommend) the answer for your problem is looking as easy as this: 例如,使用FluentLenium和AssertJ(我个人可以推荐一个堆栈),您的问题的答案就这么简单:

// check if element is displayed
assertThat(el("#divDuplicateBarcodeCheck")).isDisplayed();

// check if element is not displayed
assertThat(el("#divDuplicateBarcodeCheck")).isNotDisplayed();

Some more thoughts: 还有一些想法:

You should also use CSS selectors if possible instead of xPath selectors. 如果可能,还应该使用CSS选择器代替xPath选择器。 CSS selectors are less fragile , it will speed up your tests and are better readable . CSS选择器不那么脆弱 ,它将加快您的测试速度提高可读性

You should have a look at implicit waits instead of using Thread sleeps (bad practice). 您应该看看隐式等待,而不是使用线程睡眠(不好的做法)。 you can again implement helper methods like this by yourself, eg: 您可以自己再次实现这样的辅助方法,例如:

void waitForElement(final WebElement element) {
    final WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.visibilityOf(element));
}

void waitForElement(final By by) {
    final WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}

void waitForElementIsInvisible(final By by) {
    final WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(by));
}

or (what i would recommend) use a library for that, for instance Awaitility 或(我会建议)为此使用一个库,例如Awaitility

If your are looking for a more extended example you can have a look here: 如果您正在寻找更扩展的示例,可以在这里查看:

Seems there is an extra / at the end of the which you need to remove. 似乎需要删除的末尾有一个多余的/ Additionally, you need to induce WebDriverWait for visibilityOfElementLocated() . 此外,您需要为WebvisibilityOfElementLocated() OfElementLocated visibilityOfElementLocated()引入WebDriverWait So effectively your line of code will be: 因此,您的代码行实际上将是:

String abc = new WebDriverWait(d, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[contains(.,'Leave Balance')]//following::div[@id='applyleave_leaveBalance']"))).getAttribute("style");
System.out.println(abc);
if(abc.contains("block"))
{          
    d.findElement(By.id("duplicateBarcodeCheck")).click();   
    System.out.println("duplicate barcode Close");                                              
}
else    
{    
    System.out.println("Barcode selected");
}

Virtually, if() block is still an overhead and you can achieve the same with: 实际上, if()块仍然是开销,您可以使用以下方法实现相同的目的:

try {
    new WebDriverWait(d, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//label[contains(.,'Leave Balance')]//following::div[@id='applyleave_leaveBalance']"))).click();
    System.out.println("duplicate barcode Close");  
} catch (NoSuchElementException e) {
     System.out.println("Barcode selected");
}

Q1. Q1。 I want to locate the display element, but the element is hidden, i have written the code for it too. 我想找到显示元素,但是该元素是隐藏的,我也为此编写了代码。

A1. A1。 As per your below code: 根据您的以下代码:

 <div id="divDuplicateBarcodeCheck" class="spreadsheetEditGui" style="z- index: 1200; width: 640px; height: 420px; top: 496.5px; left: 640px; display:block"> ==$0 

It doesn't look hidden, the problem is that your using incorrect xpath and element getter. 它看起来并不隐藏,问题在于您使用了不正确的xpath和element getter。

Use: 采用:

String abc = d.findElement(By.xpath("//div[@id='divDuplicateBarcodeCheck']"))
.getCssValue("display");

Instead of: 代替:

 => .getAttribute("display");

Alternative method using JavascriptExecutor: 使用JavascriptExecutor的替代方法:

JavascriptExecutor jse = (JavascriptExecutor) d;
String displayProperty = (String) jse.executeScript("return 
document.getElementById('divDuplicateBarcodeCheck').style.display");
System.out.println("Display property is: "+displayProperty);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果我通过Selenium Webdriver和Java知道相应的文本,如何提取DOM元素的ID属性 - How to extract the ID attribute of a DOM element, if i know corresponding text through Selenium Webdriver and Java 如何使用 Selenium 和 Java 更改元素的样式属性的显示属性 - How to change the display property of the style attribute of an element using Selenium and Java 如何使用javascript使用java使用selenium Webdriver设置所选Web元素的属性? - How to use javascript to set attribute of selected web element using selenium Webdriver using java? 如何使用 Selenium WebDriver 验证元素中是否存在属性? - How to verify an attribute is present in an element using Selenium WebDriver? 如何使用 Selenium WebDriver 使用 Java 确定元素的颜色? - How to determine the color of an element using Java using Selenium WebDriver? 如何使用Selenium和Java中的属性搜索元素 - How to search for an element using an attribute in selenium and java 如何使用 Java 在 Selenium WebDriver 中检查元素是否可点击 - How to check if element is clickable in Selenium WebDriver using Java 如何在 selenium webdriver java 中使用 css 选择器定位元素? - How to locate element using css selector in selenium webdriver java? 如何使用Java使用Selenium WebDriver访问不可见的无序列表元素 - How to access invisible Unordered List element with Selenium WebDriver using Java 如何使用Selenium Webdriver + Java确定Web元素的输入类型? - How to determine the input type of a web element using Selenium Webdriver + Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM