UI自动化测试常用的定位方式
- driver.find_element_by_xpath()
- driver.find_element_by_css_selector()
两种定位方式比较:
- xpath:代码量多,不易维护
- css_selector:代码量少,简单易维护
区别:
- xpath可以直接角标定位,CSS Selector不可以;
- 可以向上取父元素也可以向下取子元素,CSS Selector只能向下取;
- 可以通过标签的文本进行定位,CSS Selector不可以;
什么时候用xpath/css?
在网上查找答案,JeffC的观点是,按他的经验,首先10%通过ID定位,其次80%通过CSS Selector定位,剩下10%通过Xpath定位。
My general locator strategy is ID first, CSS selector for everything else. When nothing else works I use XPath. It will vary from site to site but in my experience, IDs are maybe ~10% of my locators. CSS selectors are probably ~80% and the last 10% is XPath. I generally use XPath for when I need to locate an element by the contained text and very rarely DOM traversal. An example of my XPath usage might be I need to find an element in a TABLE relative to a row label, e.g. the price of cheese in a table row where the first cell contains “cheese” and the third cell contains the price.
详见stackoverflow网站中 cssSelector vs XPath for selenium话题
个人建议:
研发平常可能为了标签变得更好看,改变标签的层级关系,所以使用层级关系定位受研发修改影响大,不稳定;
另一方面,页面除非大改版,是不会改变标签属性的;因此建议通过属性定位。
什么时候通过级关系定位?
标签没有属性,无法通过属性定位元素。此时可以通过找到所有这个标签,然后取角标(Xpath)找到元素。