Why one should prefer using CSS over XPath in IE?

后端 未结 4 478
再見小時候
再見小時候 2020-12-03 02:18

I am working on an application which is compatible only with IE7 and IE8. I didn\'t know why but some suggested to use CSS over XPath while identifying the elements in IE. W

相关标签:
4条回答
  • 2020-12-03 02:49

    According to Ashley Wilson's report from sauce labs:

    Pros:

    1. They’re faster
    2. They’re more readable
    3. CSS is jQuery’s locating strategy
    4. No one else uses XPATH anyways!

    It's a bit outdated, however here are the numbers:

    image from cause lab's web site

    Personally, I would argue about (2)-nd statement, I must agree with the rest.

    Cons:

    1. No "bottom up" navigation. XPath has elem\..\another_elem
    2. Is Sizzle injected? Or Browser's CSS locator parser is used? Depends on the browser, and there are inconsistencies.
    0 讨论(0)
  • 2020-12-03 02:51

    Brevity and Clarity are other reasons, in addition to speed.

    In addition to speed, I find that css is usually shorter and cleaner and easier to read. For example:

    xpath:

     //ol[@class='choice-group'//li//label//input
    

    vs

    css:

     css=ol.choices-group li label input
    
    0 讨论(0)
  • 2020-12-03 02:55

    The biggest reason for suggesting CSS selectors over XPath in IE is performance. IE does not provide a native XPath-over-HTML option as does Firefox and Chrome. It does, however, provide a native CSS selector engine, which will always be faster than the JavaScript-only XPath engine implementation used in the IE driver. And the performance comparison isn't even close. I've seen it measured as much as an order of magnitude slower for XPath locators than CSS selectors (though I can't find the citation at the moment). This is particularly true in versions of IE before 9, where the IE JavaScript engine was vastly slower than the Chakra JavaScript engine introduced in 32-bit IE9.

    0 讨论(0)
  • 2020-12-03 02:55

    Using CSS locator is the best option, not only on IE, also on FF and Chrome. Also, xpath is always the worst choice, because it needs to parse the whole page to find a simple element, so if you want performance in your tests and you can avoid it, just do it.

    Also, if you are using pageObjects I strongly recommend you to use cacheLookup, so the element will be located just once:

    @CacheLookup
    @FindBy(id="doLogin")
    private WebElement loginButton;
    

    Personally, I do the following:

    • If element has css class, use this locator
    • If element has name or id, use this locator
    • If none of the above is present, and you can not use linkText or another locator, go for xpath.
    0 讨论(0)
提交回复
热议问题