Selenium 2 - Get Number of Rows in a Table

I was recently browsing through some of the questions on StackOverflow and came across this question. The question was around how you would count the number of rows in a table using Selenium 2 and Python. If you need a bit of a background to Selenium 2, I have written a little about it before.

Now although the question was about the Python API, I wanted to try and get it working using the C# API. It was a pretty basic question and I wasn't really working on anything at the time so I started to have a look. Selenium has got built in support for XPath and this makes the solution to the question a lot easier.

Start off by navigating to the page that you want to verify.

Then find the element you are working with - in our case it will be a table.

Next, let's use a little Lambda Expression to find the elements that match the XPath - tr

We can wrap this all together in a method.

And call it like so in a test using the new class we have created.

You could also use this method to count any number of tags in HTML. I've put this all together in a little helper class and included a sample on how to count the number of options in a select list. The full solution source code is available for download here.