简体   繁体   中英

C# Selenium Webdriver Count Xpath Elements / null check

How would you convert the count of xpath to int?

int example = driver.FindElement(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count;

I picked this up from question: Does anyone know why GetXpathCount() doesn't work in C#?

I can't seem to get it to work, I tried dumping the above to a list and counting the list but this also wouldn't work.

Also sort of off topic but is there a way to check if driver.FindElement(By.XPath("exp")) == null? because if it dose = null it will throw a null reference error.

You can use FindElements if you have a same locator for more than one element.

It will return ReadOnlyCollection, using that you can get count of elements:

int example = driver.FindElements(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count();

You are looking for .FindElements .

After all, look at the method name of what you are using: FindElement . (no plural)

Therefore, the count will always be 1 ;)

Check out .FindElements , this will have a .Count property (because it's essentially a List that is returned).

As for the null checking, that is down to you but it is unneeded. The source code of Selenium shows it will never be null returned from there. It's either going to be the element you asked for, or an exception is thrown if it has trouble getting it.

So a null check would be defensive, but wasteful. Even more so since that .FindElements will just return an empty collection if it has trouble getting the element you are asking for (ie compared to throwing an exception).

Therefore realistically speaking, you'd only get a NullReferenceException if driver was null (which would mean your entire test fails).

int numberOfElements = driver.FindElements(By.XPath("(//td[contains(@sorttable_customkey, '" + Account + "')])/preceding::a[1]")).Count;

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