Highlighting Web Elements with Selenium WebDriver C#

Selenium WebDriver is a test automation tool used to drive web applications (hence the name) :D. It works at the user interface level, so it will click on buttons, enter text into text fields, perform validations for us etc. as well as a multitude of other functions.

One issue, however, with WebDriver, is that when running your scripts, it can be difficult to see what object or element, WebDriver is trying to interact with, since what WebDriver is doing under the bonnet, is sending and receiving HTTP requests, so essentially, we are not actually going to SEE anything happen, it will just… HAPPEN!

However, we can write some extra code that will allow us to see what object is being interacted with at specific points in time. Although, we may need to implement some JavaScript code for this to work as WebDriver currently has no function for this.

Create a new test class:

Firstly we will need to create a class and write some WebDriver code, to interact with an object.

In the code snippet above we have a simple class that;

  1. Launches Chrome and navigates to base url
  2. Clicks a link
  3. Closes Chrome

Now we can add the code to highlight the element we are trying to interact with (the Login Link).

Highlight Element Method:

In order to highlight an element, we need to implement some JavaScript code. I believe, the most efficient way to do this, is to store the code inside a reusable method, so that we can improve maintenance and also re-usability.

Within the same class, just outside of the Test method, I have a section for my helper methods. Usually this method may be stored in a completely separate class, but to keep this demonstration simple, we will keep it stored in the same class.

Call the Method:

Now in order to execute the code within that method we need to call it from within our test method. We also must pass in the element we wish to highlight, as an argument to the method.

NOTE: I have also placed a short delay, just after my call to the method, so I can actually see it highlighting the element.

Once we have done this, we can run our test.

Run your test:

When we execute our test now, we will be able to see what object, WebDriver is about to interact with, depending on the styling we have used in our method (we have just gone for a simple red border and yellow background, but you can adjust this as you please).

As you can see in the image above, the element is being highlighted so we can see what object, WebDriver is trying to interact with.

Completed Code:

Here is the completed code:

For more information regarding Selenium WebDriver, please see our:

Selenium Courses