Web自动化测试:xpath元素定位深入讲解

2022-10-1821:19:58后端程序开发Comments820 views字数 1002阅读模式

一、Xpath高级用法基础格式

  • 格式
    /轴方法::标签名[标签属性]
  • 实例
    //div/parent::span[@name=‘interName’]
  • 实例解释:
    定位span标签,span标签是div标签的父级,且span标签的name属性值为:interlNmae

二、基础格式详解

2.1层级路径格式文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 讲解
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 实例
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

2.2标签位置以及标签属性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 讲解
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 实例
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

2.3 xpath轴方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 讲解
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

  • 实例
Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

2.4常用运算符文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

三、实例演示

  • 常见场景:输入框定位有时候经常遇到输入框表单很多,也没有唯一标识id等,chrome复制的xpath非常的长,而且容易失效,但是如果根据输入框前的字段名称来作为标识,那定位就比较稳定了。这里我来演示的是百度的注册页面,这里输入框的输入通过字段名称来作为唯一标识,来定位输入框

xpath = //label[text()=‘用户名’]/following-sibling::input[last()]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

Web自动化测试:xpath元素定位深入讲解文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html

代码:from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.set_page_load_timeout(15)
driver.get("https://passport.baidu.com/v2/?login")

# 点击注册
driver.find_element("xpath", "//a[text()='立即注册']").click()

# 切换页签
all_handle = driver.window_handles
driver.switch_to.window(all_handle[1])

# 定位标签
driver.find_element("xpath", "//label[text()='用户名']/following-sibling::input[last()]").send_keys("川石学院")
driver.find_element("xpath", "//label[text()='手机号']/following-sibling::input[last()]").send_keys("13691729932")
driver.find_element("xpath", "//label[text()='密码']/following-sibling::input[last()]").send_ke
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28408.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/28408.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定