转载一篇灰蓝的文章,原文地址:http://blog.csdn.net/huilan_same/article/details/52806985

XPath、CSS定位速查表

19、Selenium + Python 实现 UI 自动化测试-XPath and CSS cheat sheet

HTML版如下:

描述 Xpath CSS Path
直接子元素 //div/a div > a
子元素或后代元素 //div//a div a
以id定位 //div[@id=’idValue’]//a div#idValue a
以class定位 //div[@class=’classValue’]//a div.classValue a
同级弟弟元素 //ul/li[@class=’first’]/following-sibling::li ul>li.first + li
属性 //form/input[@name=’username’] form input[name=’username’]
多个属性 //input[@name=’continue’ and @type=‘button’] input[name=’continue’][type=’button’]
第4个子元素 //ul[@id=’list’]/li[4] ul#list li:nth-child(4)
第1个子元素 //ul[@id=’list’]/li[1] ul#list li:first-child
最后1个子元素 //ul[@id=’list’]/li[last()] ul#list li:last-child
属性包含某字段 //div[contains(@title,’Title’)] div[title*=”Title”]
属性以某字段开头 //input[starts-with(@name,’user’)] input[name^=”user”]
属性以某字段结尾 //input[ends-with(@name,’name’)] input[name$=”name”]
text中包含某字段 //div[contains(text(), ‘text’)] 无法定位
元素有某属性 //div[@title] div[title]
父节点 //div/.. 无法定位
同级哥哥节点 //li/preceding-sibling::div[1] 无法定位


小结:(个人加)

1、/ ,是说在当前元素子元素找

2、// ,是说在子元素和孙元素(所有后代元素)都找,1和2 ,找的范围是不同的。

3、//xxx[@yyy='zzz'] , 找xxx这个类型的元素(这个可以是通配符*),这个类型需要满足什么要求呢?他有一个属性yyy且值等于zzz。注意写法,属性前面有@符号,值是被引号引起来的。

4、使用and,//input[@name=’continue’ and @type=‘button’]。见过一次,需要通过两个属性的值可以唯一定位到目标元素。

5、//xxx[1],根据index来定位元素,这个尽量少用,考虑到定位器的健壮性。可以参考我那篇翻译的文章

6、 //xxx[last()],定位最后一个xxx元素

7、//xxx[continues(@yyy,'zzz')],yyy属性值中包含zzz字符。

    //xxx[starts-with(@yyy,'zzz')],yyy属性值中以zzz字符开始,这个常用在需要定位元素有动态id的时候

    //xxx[ends-with(@yyy,'zzz')],yyy属性值中以zzz字符结束

注意starts-with,ends-with,是复数,不是start-with,end-with

8、//xxx[continues[text(),'zzz'] , text中包含某字段;这个在某种情况下很有用;

相关文章:

  • 2021-05-31
  • 2021-11-30
  • 2022-12-23
  • 2021-10-03
  • 2021-10-19
  • 2021-08-24
  • 2021-10-21
  • 2021-07-20
猜你喜欢
  • 2021-07-06
  • 2022-12-23
  • 2021-04-08
  • 2021-06-11
  • 2021-08-18
  • 2021-05-21
  • 2021-09-15
相关资源
相似解决方案