当前位置:首页 » python教程 » 正文

UI自动化定位常用实现方法代码示例

看: 903次  时间:2020-12-07  分类 : python教程

8大基础定位

  • driver.find_element_by_id() # id定位
  • driver.find_element_by_name() # name定位
  • driver.find_element_by_class_name() # class名称定位
  • driver.find_element_by_tag_name() # 标签定位
  • driver.find_element_by_xpath() # xpath定位
  • driver.find_element_by_css_selector() # css定位
  • driver.find_element_by_link_text() # a标签的文本定位
  • driver.find_element_by_partial_link_text() # a标签的局部文本定位

xpath定位

  //*[]:// 相对定位 * 匹配任意标签

  第一种:id\class\name\其他属性,精确匹配

driver.find_element_by_xpath("//*[@id='']") # id与id的值
driver.find_element_by_xpath("//*[@class='']") # class和class的值
driver.find_element_by_xpath("//*[@name='']")     # naem和值
driver.find_element_by_xpath("//*[@shuxingming='']") # 属性名和值

  第二种:模糊匹配\层级\索引\逻辑运算

  模糊匹配:

driver.find_element_by_xpath("//*[contains(text(),'测试')]")     # 包含某些字符
driver.find_element_by_xpath("//*[starts-with(text(),'测试')]")   # 以某些字符开头
driver.find_element_by_xpath("//*[ends-with(text(),'测试')]")     # 以某些字符结尾
driver.find_element_by_xpath("//*[matchs(text(),'测试')]")      # 正则匹配

  层级:

driver.find_element_by_xpath("//*[@id='']/p")

  索引:

driver.find_element_by_xpath("//*[@id='']/option[0]")

  第三种:绝对定位

  html/body/heard/div/divdiv/ul/li[2]/a 不推荐

css定位

  第一种:id\class\标签名

#:id

.:class

driver.find_element_by_css_selector("#username") #id为username
driver.find_element_by_css_selector(".username") #class为username
driver.find_element_by_css_selector("iframe") #标签名为iframe

 第二种:

索引:

driver.find_element_by_css_selector("selet#nr>option:nth-child(1)") #标签名:nth-child(1)来定位子元素

层级:

driver.find_element_by_css_selector("selet#nr>option") #标签名:nth-child(1)来定位子元素

逻辑运算:

driver.find_element_by_css_selector("input#nr[id=''][class='']") #不用and连接,写在一起即可

定位多组元素

使用 find_elements ,结果为列表,使用下标索引方式取值

names=driver.find_elements_by_name("username")
print names[1]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

标签:selenium  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!