python-selenium -- xpath定位方法详解

一、xpath基本定位用法

  1.1 使用id定位 -- driver.find_element_by_xpath('//input[@id="kw"]')

  

  1.2 使用class定位 -- driver.find_element_by_xpath('//input[@class="s_ipt"]')

  

  1.3 当然 通过常用的8种方式结合xpath均可以定位(name、tag_name、link_text、partial_link_text)以上只列举了2种常用方式哦。

二、xpath相对路径/绝对路径定位

  2.1 相对定位 -- 以// 开头 如://form//input[@name="phone"]

  

  2.2 绝对定位 -- 以/ 开头,但是要从根目录开始,比较繁琐,一般不建议使用 如:/html/body/div/a

  

三、xpath文本、模糊、逻辑定位

  3.1【文本定位】使用text()元素的text内容 如://button[text()="登录"]

  

  3.2 【模糊定位】使用contains() 包含函数 如://button[contains(text(),"登录")]、//button[contains(@class,"btn")]

  

  3.3 【模糊定位】使用starts-with -- 匹配以xx开头的属性值;ends-with -- 匹配以xx结尾的属性值  如://button[starts-with(@class,"btn")]、//input[ends-with(@class,"-special")]

  3.4  使用逻辑运算符 -- and、or;如://input[@name="phone" and @datatype="m"]

四、xpath轴定位

  4.1  轴运算

  ancestor:祖先节点 包括父
  parent:父节点
  prceding-sibling:当前元素节点标签之前的所有兄弟节点
  prceding:当前元素节点标签之前的所有节点 
  following-sibling:当前元素节点标签之后的所有兄弟节点
  following:当前元素节点标签之后的所有节点 
 
  使用语法: 轴名称 :: 节点名称
  使用较多场景:页面显示为一个表格样式的数据列
  如:
  

  

注意:

#定位 找到元素 -- 做到唯一识别
#优先使用id
#舍弃:有下标的出现、有绝对定位的出现、id动态变化时舍弃
 

猜你喜欢

转载自www.cnblogs.com/simran/p/9234783.html