Highlighting Elements in Selenium WebDriver
Here’s how you can highlight elements in the browser using Selenium WebDriver with Java.
If you want to skip ahead, I’ve got a working example in a GitHub repo that uses JBehave as the test runner. This way, you can build the project yourself, see a “real-life” example and tinker with it.
I’d like to thank Iain for his blog post on highlighting elements.
First of all – if you are building an automation framework at your organisation – it’s sometimes a good idea to wrap certain WebDriver calls through a bespoke, lightweight common library.
- It helps enforce standards inside your organisation.
- It can reduce code.
- It increases code readability.
- Particularly difficult things to automate (e.g. hover and click, drag and drop) can be used again and again by different project teams.
- A solid common library makes tests more stable as it is harder to introduce silly errors into your code.
- It is much much easier to update common methods with the latest API additions and best practise.
We need two methods to achieve our aim.
First, we need to create a setAttribute() method similar to the WebDriver getAttribute() method. The WebDriver API does not have this built in because it is specifically designed to mimic the user’s interactions with the browser – and the user cannot change attribute values (through “normal” use).
So we can call executeScript() directly in our method without worrying about casting it first.
If you don’t use JBehave then this should do the trick:
Now we just need to create a highlight method that uses setAttribute().
It’s not the prettiest code but the effect is pretty cool.
You could parametrise the colours if you wanted to. I also feel that the wait time is enough to clearly notice what’s going on without slowing tests down too much.
Using it in your code.
I have a working example in a GitHub repository. You just need Maven and Firefox installed.
Simply follow the running instructions to see the highlight method in action while searching for things on Amazon.