What is the most efficient selector to use with findElement()?

前端 未结 4 1424
陌清茗
陌清茗 2020-12-16 05:26

When working with Selenium web testing, there are a few ways to identify WebElements.

In my experience, I have used the following selectors:

  • Cl
4条回答
  •  猫巷女王i
    2020-12-16 06:19

    Locators should be descriptive, unique, and unlikely to change. So my priority is as follows:

    1. ID - You'll get the exact element you want and it can be descriptive and won't be changed by mistake.
    2. Class - Very descriptive, probably unique in context of parent element.
    3. CSS - Better performence than XPath - see Dave Haeffner's great benchmark.
    4. XPath - Has capabilities that CSS doesn't like Axis e.g. ::parent and functions like contains().

    I would avoid LinkText and TagName as they tend to cause unexpected failures due to very generic filtering.

    Note on CSS and XPath: Using these with something like //div/li[1]/*/span[2] or div > li:nth-child(1) should also be avoided as they depend on the rendering and prone to changes.

提交回复
热议问题