Selenium之Xpath VS CSS Selector

在这里插入图片描述

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)找到元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值