2

If there is an id available for an object in a page, find element by ID or CSS - which is faster?

element(by.id("btnButtonID")) OR element(by.css("#btnButtonID")

Since we can identify any objects using CSS locator, is it a standard practice to use only CSS locator in our page objects? Does it help to look the code readable and cleaner?

  • 1
    speed should be secondary to future uniquess of selector so ID should be chosen. time diff compared to overall time of test is negligble – Michael Durrant Sep 19 at 20:20
  • a developer ~wouldn't~ shouldn't add another element with the same ID. However an app developer or design/layout (UI) developer might add another element using the same class. that's what classes are for. Maybe a new section with another button with same styling is added later – Michael Durrant Sep 19 at 20:22
3

Any WebDriver will use Json Wire Protocol to interact with the browser. The protocol defines 5 locator strategies:

  1. css selector,
  2. link text selector,
  3. partial link text selector,
  4. tag name,
  5. xpath.

w3 Webdriver locator strategies

As you can see there is no "Id". By.Id is sugar syntax added by Selenium and other WebDriver implementations. Under the hood it just translates By.Id to either css or xpath selector. So to asnwer your question - a css selector using the ID might be slightly faster as you ommit the mapping.

0

It depends, mainly on the implementation of the WebDriver. Old benchmark shows in some cases CSS selectors are faster and the other way around. See: https://stackoverflow.com/questions/38716233/in-selenium-webdriver-which-is-better-in-terms-of-performance-linktext-or-css

I think it doesnt really matter, unless you test old IE version, which have very slow selectors. In modern browsers like Chrome the speed difference will be milliseconds. So pick the one you find the most readable.

-1

Per our experiences, the faster orders as follow.

  1. ID/Name
  2. CSS
  3. Xpath
  4. ...
-1

Locating elements by id is faster than css. Because :

  • id of an elements is more specific than css of an element.

For example :-

  • element will have id like "idOfName"

  • but its css may have specifier that is similar or is matching to the css's of other elements like its name, color, font etc.

  • "#id.name" css has "id" specifier which can be a class which most the elements use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.