简体   繁体   中英

How to count only elements displayed on WebPage. Selenium

I have a web page with two tabs.

When I get count of Elements on one tab it gives me count for both the tabs but not on the one I have clicked on.

So If I want to check an element that is present of Tab1 and not on Tab2 I am not able to do that as I am getting same results on both the tabs.

if (driver.FindElements(By.XPath("//div[contains(text(), 'Dummy Text')]")).Count != 0)
{
    // Failed Test message ;
}

On Tab1 I am expecting count should be 0 as this text is not displayed and on Tab2 count should 8 but on both the tabs count is 8.

How can I get count of elements which are displayed on my page and not in the background?

I am sure it is because of tabs on web page and selenium is considering both tabs as same web page content.

Selenium will return all objects in the DOM not just those visible to the user.

I do not believe there is any XPath or CSS selector which allows you to select only visible elements. I can think of a potential nasty XPath which ensure that no parent had display:none but do not know if that would actually work and sounds too horrible and complex to even contemplate.

You need to iterate through each returned element and check that "displayed" returns false. I would be tempted to extend the Driver class to have a FindDisplayedElements method which would wrap this functionality for you.

However this approach could be expensive in terms of API calls if you are using RemoteWebDriver. An alternative could be to ensure a parent object is hidden, as all children would also inherit that behaviour

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM