18

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.

Tejas
  • 391
  • 2
  • 7
  • 19

3 Answers3

36

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.

JimEvans
  • 27,201
  • 7
  • 83
  • 108
  • Interesting. I didn't know CSS selectors are faster than XPath on IE (XPath on IE is terrible is a known). Can you quote some references? I am interested in learning this further. Is this observation IE specific? – Ashwin Prabhu Aug 02 '12 at 16:28
  • That is not IE-specific, browsers are generally very fast to resolve CSS selectors in order to be able to style the HTML accordingly. – D.R. Jul 29 '14 at 14:31
  • `By.id("brandlogo")` or `By.xpath("//*[@id='brandLogo']")`, which one is fast. Both are directly looking for `id='brandlogo'` – paul Dec 28 '15 at 08:12
  • 1
    @AshwinPrabhu In the book "Selenium Testing Tools Cookbook" by Unmesh Gundecha (2012 version) it states that css selectors -in general- are faster than xpath because xpath selectors are bidirectional, meaning they can find a parent based on the child, whereas css selectors cannot. – MentallyRecursive Dec 12 '19 at 17:16
  • @MentallyRecursive Thanks! – Ashwin Prabhu Dec 13 '19 at 15:18
2

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()

Alpha
  • 13,320
  • 27
  • 96
  • 163
user3487861
  • 340
  • 2
  • 2
2

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.

Ruchi Dhole
  • 95
  • 2
  • 12