How can I count the number of elements that match my CSS selector?

我的梦境 提交于 2019-11-29 02:55:00

As far as I am aware you can't do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:

verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2

In Selenium RC (Java) this would look more like

assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);

This is now also implemented (without any extra Javascript magic needed) in Selenium Webdriver API Since google still links to this question as a top result, even though Selenium RC has been replaced by Webdriver, hopefully this saves someone time.

Example java code:

int locatorElementSize = driver.findElements(By.cssSelector("yourCSSLocator")).size();

With newer versions of Selenium, there is a function GetCSSCount(string locator). Just thought an update to this question would be useful

vinnybad

This should be relatively simple. You can do it multiple ways but I would suggest using the getEval(...) in DefaultSelenium.

Write some JavaScript that:

  1. gets all elements by id: ext-gen3506
  2. iterates through all elements and checks to see if it's enabled
  3. if it's enabled, increment a count
  4. "return" the count.

Generally, getEval(...) will return the value of the last statement that ran... so that should give you the count.

Since Selenium is part of Firefox and the latter is supporting Selectors API one could simplify counting matches of a CSS locator using a test like this:

verifyEval | window.document.querySelectorAll("your#css > selector.here").length | 4

In this example count is verified to be 4, of course.

David

Here's another solution, using javascript, similar to post about Selector API / window.document.querySelectorAll:

http://blog.eviltester.com/2010/03/a-simple-getcsscount-helper-method-for-use-with-selenium-rc.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!