playwright locator 定位方法实践,依据 官方文档
Text selector–文本定位
单独使用文本
1, text = “xxx“这种写法,是需要文本完全匹配
t=page.locator(“text=‘Log in button’”)
t.count() = 1 可匹配到一个元素
t=page.locator(“text=‘Log in’”)
t.count() = 0 未匹配到任何元素
特殊写法 t=page.locator(”‘Log in button’”) 等价于 t=page.locator(“text=‘Log in button’”)
2, text = xxx 这种写法,是模糊匹配 t=page.locator(“text=Log in”)
t.count() = 2 可匹配到两个元素,这两个元素都包含Log in
3, text = /xxx/i 是正则匹配方法 t=page.locator(“text=/Log.*?button/i”)
t.count() = 1 可匹配一个元素
配合css selector 使用文本
1,t = page.locator(“div.sample2 :has-text(‘第四’)”) t.count() = 3 可匹配三个元素, 匹配从div.sample2(结果不包含此层)开始到查到文本之间中所有层的元素
2,t=page.locator(“div.sample2 :text(‘第四’)”)
t.count() = 1可匹配到一个元素, 在selector div.sample2下 包含文本 第四 的元素
selector :text(“xxx”) text的用法同上面的text = xxx
3,t=page.locator(“div.sample2 :text-is(‘第四’)”)
t.count() = 0 未匹配到元素,原因是需要精确匹配 ,文本用法同上面的 text=‘XXX’
t=page.locator(“div.sample2 :text-is(‘我是第四层’)”)
t.count() = 1 匹配到元素