How to build a method to iterate through WebElements and return the one that is displayed using Selenium & Java?

前端 未结 1 1714
既然无缘
既然无缘 2021-01-28 06:26

So, the page is filled with a lot of similar properties like these two elements below. Examples:

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-28 06:45

    I'll show how I would go about it, but the problem might be a problem with selenium not always returning isDisplayed() correctly depending on the element type.

    public WebElement getFirstVisibleElement(List elements) {
        for (WebElement ele : elements)
            if (ele.isEnabled() && ele.isDisplayed())
                return ele;
        return null;
    }
    

    A more reliable method of checking if a web element is displayed is to check its dimensions (height and width). If they are both zero, it's not displayed.

    public WebElement getFirstVisibleElement(List elements) {
        for (WebElement ele : elements)
            if (ele.isEnabled() && ele.getSize().getHeight() > 0 && ele.getSize().getWidth() > 0 )
                return ele;
        return null;
    }
    

    0 讨论(0)
提交回复
热议问题