Why Selenium/WebDriver sometimes fail to find element

In the last couple days I am frustrate of my unstable selenium tests. In my local machine, all tests passed without issue. But when run the tests on our build server, tests fail randomly. The most common error I got are:

  • Fail to find element even I can see the element in my browser
  • Fail to find the javascript alert popup

If you do a google, you can see a lot of post complain about it. And Simon Stewart, the WebDriver author, even have a blog topic about it.

After hours research and testing, I finally make my tests stable on our build server. Here is some experience someone may interested:

  1. Make sure your page in fully load by WebDriver: WebDriver has a blocking API. It means method should not return when the page is loading. But this is only true when calling WebDriver.Navigate().GoToUrl(), not when clicking ! So when you click a button and redirect to another page, your element may not be initialized when the method return. In my tests, most of fail to find element is caused by this. What I do is reload the page again after the clicking and make sure WebDriver load the page fully before it my method return.  Not perfect, but it works.
  2. Make sure your iframes inside the page are fully load as well. Similar issue as #1, when WeDriver load a page with iframes. The method return does not means all frames are loaded. If you want to use elements inside the frame, you need to make sure the frame page is fully load by yourself. In my tests, I wait the last element in my frame is present before I use the frame.
  3. If your javascript alert popup is raise by ajax etc, make sure WebDriver Alert API don’t try to catch the javascript alert popup too early. Basically before alert be called, change a “tag” dom element in the page. Use WebDriver wait  API to check the “tag” element present before catch the alert.

In summary, before you write any Selenium/WebDriver tests, make sure you understand what blocking API can do and cannot do. Design your tests carefully and make sure don’t fall into above traps.

This entry was posted in .Net, Ajax, JMeter. Bookmark the permalink.

1 Response to Why Selenium/WebDriver sometimes fail to find element

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s