cssSelector vs XPath for selenium

前端 未结 3 1108
刺人心
刺人心 2020-12-10 20:57

As per my understanding, CSS selector traverses through the DOM. Because CSS files will not have any info about element position then why cssSelector is faster then

3条回答
  •  独厮守ぢ
    2020-12-10 21:28

    I always use xpath. With xpath I've got the ability to use any of the attributes of an object, including it's ID or Name. I can use combinations and subsets of them and invoke xpath's powerful language if I need it.

    From my experience, navigating the DOM tree using xpath is a better way of locating an object than using CSS which is after all meant to describe only how it is displayed.

    As for speed comparison, I'd reckon it would depend on the complexity of the expression. Does find_element_by_id('myID') or find_element_by_xpath(@id='myID') or find_element_by_css_selector ('myID') invoke different engines and produce different response times?

    Much of the bad press I've heard and read about xpath is because people use hardcoded paths like //div[1]/div[2]/a[3] which is brittle. A more robust xpath expression like //div[@id='main']//a[@href='xpath_nodes.asp'] could be written.

提交回复
热议问题