Playwright基本定位
css定位
如在css定位为#kw的位置输入内容,如下写法均可:
page.locator('#kw').fill("输入的内容")
page.locator('css=#kw').fill("输入的内容")
page.fill('#kw','输入的内容') #可以不写css=或xpath=,会自动判断是cssg还是xpath
如在css定位为#su的位置点击,如下写法均可:
page.locator('#su').click() page.click('#su') page.click('css=#su')
xpath定位
如在xpath定位为//*[@id='kw']的位置输入内容,如下写法均可:
page.locator("//*[@id='kw']").fill("输入的内容")
page.locator('xpath=//*[@id='kw']').fill("输入的内容")
page.fill("//*[@id='kw']",'输入的内容')
如在xpath定位为//*[@id='su']的位置点击,如下写法均可:
page.locator("//*[@id='su']").click()
page.locator('xpath=//*[@id='su']').click()
page.click("//*[@id='su']")
text文本定位
对于界面上的文本,可用playwright的文本定位方式来定位
page.click("text=xxx") #文本没加引号,为模糊匹配,大小写不敏感
page.click("text='XXX") #文本加了引号,为精确匹配,大小写敏感
如下截图,文本定位a标签


如下图,文本定位按钮


组合定位
组合定位可用以上三种方式的任意组合来定位,中间有 >> 隔开即可
比如根据如下的元素定位百度按钮

如下组合定位均可

内置定位器
• page.get_by_text() #通过文本内容定位

• page.get_by_placeholder() #按占位符定位输入



• page.get_by_test_id() #根据data-testid属性定位元素(可以配置其他属性)
浙公网安备 33010602011771号