xpath语法的使用(以selenium为例)

"""
xpath定位
1. 路径选择
 / 表示根节点
 /html 表示选择根节点下的html节点
 /html/body/div 表示选择根节点下的html节点下面的body节点下面的div节点
 //div/p 选择所有div下的直接子节点p元素
 //div//p 选择所有div下的所有p元素
 //div/
 
2. 属性选择 [@属性名="属性值"]
 //*[@id="west"]  选择id为west的元素
 //div[@class="single_choice"]  选择class为single_choice的div元素
 注意:如果一个元素同时拥有class属性为 capital 和 huge_city
   css选择器中有其中一个就能找到  .capital
   但是xpath中需要完全相同才能找到  //div[@class="capital huge_city"]
   
 如果标签只有属性名没有属性值,如:<select class="multi_choice" multiple>
 //select[@multiple]
 
3. 包含字符串
 //*[contains(@style,"color")] 选择style属性值包含color的页面节点
 //*[starts-with(@style,"color")] 选择style属性值以color开头的页面节点
 //*[ends-with(@style,"color")] 选择style属性值以color结尾的页面节点(ends-with在xpath2中才支持)
 
4. 按次序选择
 //p[2] 选择p类型的第二个子元素(不是第二个子元素,并且是p类型!!)
 //div/p[2] 选择父元素为div的p类型的第2个子元素
 //div/*[2] 选择父类型为div的第二个子元素(可以是任意类型)
 //p[last()] 选择p类型的最后一个子元素
 //p[last()-1] 选择p类型的倒数第二个子元素
 
5. 范围选择
 //option[position() <= 2] 或 //option[position() > 3] 选取option类型的前两个子元素
 //option[position() >= last()-2] 选取option类型的后三个元素
 
6. 组选择
 //option | //h4 选择所有的option节点和h4节点
 //*[@class="single_choice"] | //*[@class="multi_choice"] 选择所有class为single_choice和class为multi_choice的节点

7. 选择父节点
 //*[@id="china"]/.. 选择id为china的节点的父节点
 
8. 兄弟节点
 //*[@class="single_choice"]/following-sibling::* 选择class为single_choice的所有后续兄弟节点
 //*[@class="single_choice"]/following-sibling::select 选择class为single_choice的所有后续select兄弟节点
 //*[@class="single_choice"]/preceding-sibling::* 选择class为single_choice的所有前面的兄弟节点

9. 文本选择
//*[text()="新闻"]
""" wd.find_element(By.XPATH, "/html/body/div")

 

posted on 2023-04-02 16:57  mlllily  阅读(113)  评论(0编辑  收藏  举报