Which is the best and fastest way to find the element using webdriver? By.XPath or By.ID or anything else? And why?
I have read at many places that XPath is the right candidate but just could not find the accurate reason for that.
Finding elements by ID is usually going to be the fastest option, because at its root, it eventually calls down to document.getElementById()
, which is optimized by many browsers.
Finding elements by XPath is useful for finding elements using very complex selectors, and is the most flexible selection strategy, but it has the potential to be very slow, particularly in IE. In IE 6, 7, or 8, finding by XPath can be an order of magnitude slower than doing the same in Firefox. IE provides no native XPath-over-HTML solution, so the project must use a JavaScript XPath implementation, and the JavaScript engine in legacy versions of IE really is that much slower.
If you have a need to find an element using a complex selector, I usually recommend using CSS Selectors, if possible. It's not quite as flexible as XPath, but will cover many of the same cases, without exhibiting the extreme performance penalty on IE that XPath can.
Obviously By.id()
is faster as compared to By.xpath()
as By.id()
is fast accessible. But, in By.xpath()
, it will take time for traversing.
Conclusion: By.id()
is faster as compared to By.xpath()
The faster way is obvious by using By.id(), but you also have alternative using By.name() also, it also has same speed as of like By.id(). And cssSelector also uses the id, name so its equivalent to same as searching By.id() and By.name() . The main reason for using xpath is that, each web element has the unique path assigned to it, So when the same id, name and classname are shared by two elements, then xpath is the option, as a unique solution.