背景

以简单的示例描述selenium webdriver提供的定位方法,显得更形象。对自身也算是夯实基础。

id定位

Python3+selenium总结之定位示例
上图标识部分为目标对象,通过id对其定位
Python3+selenium总结之定位示例

name定位

Python3+selenium总结之定位示例
如上图,通过对象的name属性定位输入框,但是该输入框对象的name属性非唯一。这里可以使用定位一组元素的方法find_elements_by_name()来定位。如下图。
Python3+selenium总结之定位示例
结果如下图
Python3+selenium总结之定位示例

class定位

Python3+selenium总结之定位示例
通过class定位上图标识的对象
Python3+selenium总结之定位示例
这里需要注意的一点是,如果class属性值有空格,比如class = “input icoInput”。那么取其中的”input" 或者 “icoInput”都可以实现定位,只要取的值是唯一的。

tag定位

HTML通过tag来定义不同页面的元素。在html文档结构中的节点就是tag。一个html页面中相同名称的tag太多,所以这种定位不推荐使用。
Python3+selenium总结之定位示例
通过tag定位上图标识的元素。
Python3+selenium总结之定位示例

link定位

link定位方法是专门用来定位文本链接的。
Python3+selenium总结之定位示例
上图标识部分就是一个文本链接,通过link定位方法来定位它
Python3+selenium总结之定位示例
定位结果,通过点击文本链接,打开了一个新窗口。
Python3+selenium总结之定位示例

partial link定位

partial link定位的用处是:当有些文字链接比较长,可以使用该方法取文字链接的不部分文字进行定位。
对上面【这里】文本链接使用partial link定位,效果与上面使用link定位是一样的
Python3+selenium总结之定位示例

xpath定位

xpath是xml文档中一种定位元素的语言,如果了解该语言的话,就能轻易的使用xpath定位。xpath的学习资料:
https://www.w3school.com.cn/xpath/index.asp

以下总结笔者学会的常用的xpath定位方式:

- 绝对路径定位
Python3+selenium总结之定位示例
目标对象为上图标识的对象,绝对路径的xpath语法可使用浏览器自带的Copy xpath功能获取。
Python3+selenium总结之定位示例
- 通过元素属性定位
Python3+selenium总结之定位示例
定位上图标识对象。
tips:默认选中【单程】单选框,我们的目标是定位到【往返(含缺口税】单选框,并且点击它,使得选中【往返(含缺口税】单选框。
Python3+selenium总结之定位示例
定位结果:
Python3+selenium总结之定位示例
- 通过层级与属性结合的方式定位
Python3+selenium总结之定位示例
定位目标为上图标识对象
Python3+selenium总结之定位示例
- 使用逻辑运算符
Python3+selenium总结之定位示例
Python3+selenium总结之定位示例
Python3+selenium总结之定位示例
- 使用contains方法
contains方法用于当对象属性值太长时,contains方法可以通过对象属性值的一部分来匹配。
Python3+selenium总结之定位示例
Python3+selenium总结之定位示例

- 使用text()方法
text()方法通过匹配页面上显示的文本信息来定位元素,其可以配合contain()一起使用。
Python3+selenium总结之定位示例
Python3+selenium总结之定位示例

CSS定位

CSS的特点是语法相对简洁,且定位速度比xpath快。掌握CSS的常见语法是掌握CSS定位的有效方法。

  • 通过class定位
    Python3+selenium总结之定位示例
    Python3+selenium总结之定位示例

  • 通过id定位
    Python3+selenium总结之定位示例
    Python3+selenium总结之定位示例

  • 通过标签名定位
    Python3+selenium总结之定位示例
    Python3+selenium总结之定位示例

  • 通过标签层级关系定位
    Python3+selenium总结之定位示例

  • 通过属性定位
    Python3+selenium总结之定位示例
    Python3+selenium总结之定位示例
    Python3+selenium总结之定位示例

组合定位

Python3+selenium总结之定位示例
Python3+selenium总结之定位示例
更多的CSS选择器的用法可以学习:
https://www.w3school.com.cn/cssref/css_selectors.asp

Python3+selenium总结之定位示例

相关文章:

  • 2022-12-23
  • 2022-02-27
  • 2021-12-30
  • 2023-02-17
  • 2022-12-23
  • 2021-07-22
  • 2021-12-12
  • 2021-04-12
猜你喜欢
  • 2022-12-23
  • 2021-05-15
  • 2022-12-23
  • 2021-09-29
  • 2021-11-21
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案