As the comment says, this is in C #, not Java, but the idea is the same. I have investigated this problem extensively, and the final problem is that FindElement always returns an exception when an element does not exist. There is no overloaded option that allows you to get zero or something else. That is why I prefer this decision over others.
- Returns a list of items, and then checks to see if the size of the list is 0, but you are losing functionality. You cannot do .click () in a collection of links, even if the size of the collection is 1.
- You can claim that an element exists, but often this stops your testing. In some cases, I have an additional click link, depending on how I got to this page, and I want to click it if it exists, or go otherwise.
- This will only be slow unless you set the driver.Manage () timeout . Timeouts (). ImplicitlyWait (TimeSpan.FromSeconds (0));
In fact, it is very simple and elegant after creating the method. Using FindElementSafe instead of FindElement , I don't see the “ugly try / catch block”, and I can use the simple Exists method. It will look something like this:
IWebElement myLink = driver.FindElementSafe(By.Id("myId")); if (myLink.Exists) { myLink.Click(); }
This is how you extend IWebElement and IWebDriver
IWebDriver.FindElementSafe
/// <summary> /// Same as FindElement only returns null when not found instead of an exception. /// </summary> /// <param name="driver">current browser instance</param> /// <param name="by">The search string for finding element</param> /// <returns>Returns element or null if not found</returns> public static IWebElement FindElementSafe(this IWebDriver driver, By by) { try { return driver.FindElement(by); } catch (NoSuchElementException) { return null; } }
IWebElement.Exists
/// <summary> /// Requires finding element by FindElementSafe(By). /// Returns T/F depending on if element is defined or null. /// </summary> /// <param name="element">Current element</param> /// <returns>Returns T/F depending on if element is defined or null.</returns> public static bool Exists(this IWebElement element) { if (element == null) { return false; } return true; }
You can use polymorphism to modify an instance of the IWebDriver class of the FindElement class, but this is a bad idea in terms of maintenance.
Brantley Blanchard Aug 05 '13 at 15:06 2013-08-05 15:06
source share