Today we will be talking about 'Scope of Search' for any web element and the most common practice by automation developers - 'Indexing'. | Avni

editor-img
Avni
Aug 9, 2022

Today we will be talking about 'Scope of Search' for any web element and the most common practice by automation developers - 'Indexing'. Usually while writing code to automate any UI, the most common feature we come across is 'Dropdowns'.

These can be both Static as well as Dynamic. Static dropdowns are very easy to handle as their xpath's are independent of any change on the UI but for dynamic, the case is different. Dynamic dropdowns always change depending upon the previous element we chose before selecting them.

Now, the critical part comes on how to write xpath for these when at times we get the same values inside dynamic dropdowns(e.g. country names while booking any flight will be same for 'from' and 'to' dropdowns). The most common practice used is 'Indexing' -

When selenium tries to locate any element, it will always start its searching from top left corner of the page. So now, if two dropdowns have the same value's inside them i.e. after selecting 'from' country from first dropdown, our xpath which we wrote for 'to' country will search 'to' country name in the same 'from' country dropdown itself.

Hence to overcome this situation, we give indexing to 'to' country's xpath. We will write '[2]' after the xpath so that selenium comes to know that we are addressing the second occurrence of the same value in this whole page. Now it will select 'to' country from the second dropdown(as a result of its second occurrence in the page).

Another way to handle this condition is giving parent element to the particular element's xpath. We can avoid use of 'indexing' by this approach. Selecting 'to' country from its dropdown by firstly providing xpath for its parent and then the child('to' country value) will exactly point to wherever the second occurrence of the same name is.

This way we are limiting the 'Scope of Search' to only that much area where it is required whereas usually scope is pre-defined to the whole page itself( which is not required when we want to follow this parent-child concept).


Checkout related posts on: