XPATH选择器常用语法
XPath是XML路径语言,用于在XML文档中导航和选择节点。由于HTML可以被视为XML的一种特例,XPath也可以用于HTML文档的元素定位。
1、XPath的基本语法
表达式 | 描述 |
---|---|
/ | 从根节点选择(绝对路径) |
// | 从当前节点选择(相对路径),可以是文档中的任何位置 |
. | 选择当前节点 |
.. | 选择当前节点的父节点 |
@ | 选择属性 |
2、基本XPath选择器
选择器类型 | 语法 | 示例 | 描述 |
---|---|---|---|
标签选择器 | //标签名 | //button | 选择所有指定标签的元素 |
属性选择器 | //标签名[@属性名='值'] | //input[@type='text'] | 选择具有指定属性值的元素 |
ID选择器 | //*[@id='ID值'] | //*[@id='username'] | 选择具有指定ID的元素 |
类选择器 | //*[@class='类名'] | //*[@class='btn-primary'] | 选择具有指定类的元素 |
3、XPath轴
XPath轴用于定义相对于当前节点的节点集:
//div/child::p /* 选择div的所有p子元素 */
//div/parent::* /* 选择div的父元素 */
//div/ancestor::form /* 选择div的form祖先元素 */
//div/following-sibling::p /* 选择div后的所有p兄弟元素 */
//div/preceding-sibling::p /* 选择div前的所有p兄弟元素 */
//div/descendant::span /* 选择div的所有span后代元素 */
4、XPath函数和运算符
XPath提供了多种函数和运算符,用于更精确的元素定位:
//button[text()='提交'] /* 文本完全匹配 */
//button[contains(text(),'提交')] /* 文本包含 */
//button[starts-with(@id,'btn')] /* 属性值开头匹配 */
//input[@required and @type='email'] /* 多条件与 */
//button[@type='submit' or @type='button'] /* 多条件或 */
//div[count(child::p) > 2] /* 子元素数量条件 */
5、在Playwright中使用XPath
# 基本XPath选择器
page.locator('//button').click() # 所有按钮
page.locator('//input[@type="text"]').first().fill('test') # 第一个文本输入框
page.locator('//*[@id="username"]').fill('user') # ID选择器
page.locator('//div[@class="error"]').text_content() # 类选择器# 使用XPath轴
page.locator('//label[text()="用户名"]/following-sibling::input').fill('test') # 标签后的输入框
page.locator('//input[@id="email"]/parent::div').get_attribute('class') # 父元素的类# 使用XPath函数
page.locator('//button[contains(text(), "登录")]').click() # 包含特定文本的按钮
page.locator('//tr[position() mod 2 = 1]').count() # 奇数行数量