Listen to this blog
XPath vs CSS Selectors is a captivating subject for any automation test engineer. Sometimes, teams try to convert their locators from XPath to CSS Selectors with the objective of achieving better improvement in script execution. We, at Codoid, focus on robust automated test script development to avoid false positives and negatives. Object locating performance is our next priority. If you have technical know-how of CSS Selector & XPath work, then you can write concrete object locators within a short span of time by revisiting locators thereby improving your scripts performance.
Let’s say for instance if all the XPath locators have been converted to CSS Selectors. You might have a false perception that you have accomplished something and your scripts will run fast now, which is not the case in real time. If you are not familiar in writing CSS Selector effectively, then your CSS locators won’t outperform XPath locators.
How CSS Selector selects an element
You normally write a CSS Selector from left to right. Wherein your browser parses the other way round i.e. from right to left. This is a very vital concept one needs to understand to write robust and performant CSS Selectors with ease. Always provide Class or other important locating information to the right most CSS Selector clause since your browser starts evaluating the CSS Selector from right to left. Try not to provide only tag name to right most selector clause. In case if you have provided only anchor tag to the right most clause. The parser evaluates all the anchor tags in HTML DOM to narrow down the particular anchor tag from the parent information. That’s why we insist you to provide more information to the right most clause.
Let’s say you want to locate two anchor tags which is inside the DIV tag in the below diagram. You can write the following CSS Selector – div a As we mentioned before, browser needs more information for the right most clause to identify the object quickly. As per div a CSS selector, it will parse all the anchor tags and subsequently locates the two anchor tags based on the parent information. If you provide more information for anchor tag clause, then your CSS Selector will identity the objects quickly.
How XPath works
XPath locates an element from left to right. That’s why we see some performance latency. However, XPath can traverse between descendant to ancestor and vice versa. XPath is powerful locator to identify dynamic objects. For example: if you want to identify parent nodes based child node information, then XPath will be the right choice.
We, as an automation testing company, follow test automation best practices to create robust automated test suites. Whether it is XPath or CSS Selector, we recommend you write it effectively and eventually focus on how to avoid false positives & negatives than spending time in improving object locating performance at micro level.