zoukankan      html  css  js  c++  java
  • selenium:css_selector定位详解(css selector和xpath的比较)

    selenium使用css selector和xpath的比较

    selenium提供的定位方式(常用)

    • ID
    • NAME
    • CLASS
    • CSS SELECTOR
    • XPATH
     

    推荐的定位方式的优先级

    • 优先级最高:ID
    • 优先级其次:name
    • 优先级再次:CSS selector
    • 优先级再次:Xpath
     

    针对css selector和xpath的优先级做一个简单的说明

    在项目中我们可能用的最多的是css或者xpath,那么针对这两种,我们优先选择css,原因在哪些?
    • 原因1:css是配合html来工作,它实现的原理是匹配对象的原理,而xpath是配合xml工作的,它实现的原理是遍历的原理,所以两者在设计上,css性能更优秀
    • 原因2:语言简洁,明了,相对xpath
    • 原因3:前段开发主要是使用css,不使用xpath,所以在技术上面,我们可以获得帮助的机会非常多
    题外话:据说xpath和css现在基本没有什么太大的区别了,css已经实现了大多数的xpath功能,只有个别功能没有实现。具体的数据列证还需要找更多的数据进行填充。
     
     

    定位元素的注意事项(划重点)

    • 找到待定位元素的唯一属性
    • 如果该元素没有唯一属性,则先找到能被唯一定位到的父元素/子元素/相邻元素,再使用“>”," ","+"等进行辅助定位。
    • 不要使用随机唯一属性定位
    • 最重要的是多跟研发沟通,尽量把关键元素加上ID或者name,并减少不合理的页面元素,例如重复ID这样的事情最好不要发生。

    selenium之CSS定位汇总 

    以百度首页为例:

    定位输入框

    一:单一属性定位

    1:type selector

    driver.find_element_by_css_selector('input')

    2:id 定位

    driver.find_element_by_css_selector('#kw')

    3:class 定位

    driver.find_element_by_css_selector('.s_ipt')

    4:其他属性定位

    driver.find_element_by_css_selector('[name='wd']')

    driver.find_element_by_css_selector("[type='text']")

    二:组合属性定位

    1:id组合属性定位

    driver.find_element_by_css_selector("input#kw")

    2:class组合属性定位

    driver.find_element_by_css_selector("input.s_ipt")

    3:其他属性组合定位

    driver.find_element_by_css_selector("input[name='wd']")

    4:仅有属性名,没有值也可以

    driver.find_element_by_css_selector("input[name]")

    5:两个其他属性组合定位

    driver.find_element_by_css_selector("[name='wd'][autocomplete='off']")

    6:模糊匹配属性值方法

    以百度首页点击按钮为例

    1>属性值由多个空格隔开,匹配其中一个值的方法

    driver.find_element_by_css_selector("input[class~='btn']")

    2>匹配属性值为字符串开头的方法

    driver.find_element_by_css_selector("input[class^='btn']")

    3>匹配属性值字符串结尾的方法

    driver.find_element_by_css_selector("input[class$='s_btn']")

    4>匹配被-分割的属性值的方法,如上图的class

    driver.find_element_by_css_selector("input[class|='s']")  #要求精确填写的属性值

    三:层级定位

     1:E>F    E下面的F这个元素

    driver.find_element_by_css_selector('from#form>span>input')#id是form的form下面的span下面的input

    2:E:nth-child(n)  如上图,

    driver.find_element_by_css_selector('#u_sp > a:nth-child(1)')#id为u_sp的下面的第一个a标签。

    #实测,这个定位不到,但是方法是对的,- -

    3:E:nth-last-child(n),如字面意思:倒数第几个标签

    4:E:first-child,第一个标签

    5:E:last-child,最后一个标签

    6:E:only-child,唯一的标签

  • 相关阅读:
    .NET旋转PDF并保存旋转结果到文件
    C#的抽象类和接口的区别,在什么时候使用才合适?
    [转]SQL Server中多行多列连接成为单行单列
    VBS脚本COPY指定日期文件及文件夹
    eval同时绑定两个值:通过String.Format给超链接中的两个参数赋值
    How to recover SA password on Microsoft SQL Server 2008 R2
    [转]asp.net 前台绑定后台变量方法总结:<%= %> 和<%# %>的区别
    Js得到radiobuttonlist选中值的两种方式
    Ameriscan增加一个新的client:AP_CONSO
    命令行处理pdf的利器:PDFTK.exe
  • 原文地址:https://www.cnblogs.com/haifeima/p/10138154.html
Copyright © 2011-2022 走看看