元素定位
get_by_role
通过标签的角色获取page.get_by_role("role", name="****")
常见的role的值有 link, button, heading, checkbox, list, listitem, textbox, form, table, row, cell等,具体其他role, 可查看ARIA roles
get_by_placeholder
如下所示dom结构可通过page.get_by_placeholder("Please input password")
获取
<input type="password" placeholder="Please input password" />
get_by_label
如下dom 结构都可通过 page.get_by_label("Password").fill("string")
来填入内容
<label>Password <input type="password" /></label>
# or
<label for="pwd">Password </label><input type="password" id="pwd" />
get_by_alt_text
<img alt="playwright logo" src="/img/playwright-logo.svg" width="100" />
通过alt属性值获取, page.get_by_alt_text("playwright logo")
get_by_title
<li title="status" role="menuitem" > status</li>
通过title属性值获取page.get_by_title("status")
get_by_text
通过文本来获取 page.get_by_text("Password")
<span>Password </span>
page.get_by_text("string")
模糊匹配的,不区分大小写page.get_by_text("string", exact=True)
精确匹配, 区分大小写page.get_by_text(re.compile("string"))
正则匹配
以上均可通过参数exact=True
进行精确匹配 或者通过正则匹配, 用法和get_by_text一样
get_by_test_id
<button data-testid="directions">Itinéraire</button>
-
通过data-testid属性值获取
page.get_by_test_id("directions")
-
可以通过
playwright.selectors.set_test_id_attribute("data-pw")
设置获取的属性是data-pw, 这样设置后page.get_by_test_id("directions")
表示获取的是data-pw
属性是directtions的元素
css, xpath
通过 css、xpath获取,比如locator(".css_name")
或者locator("//*[@id="tsf"]")
filter, locator, and_, or_
dom结构如下
<ul>
<li>
<h3>Product 1</h3>
<button >Add to cart</button>
</li>
<li>
<h3>Product 2</h3>
<button style='display: none'>Add to cart</button>
</li>
</ul>
filter
- has_text or has_not_text
page.get_by_role("listitem").filter(has_text="Product 2")
定位到第二个li - has or not_has
page.get_by_role("listitem").filter( has=page.get_by_role("heading", name="Product 2")
) 定位到第二个li
locator(“visible=true”)
page.locator("button").locator("visible=true")
只会匹配visible的button
and_
- 1.34以上版本才支持
- 同时匹配两个定位器
page.get_by_role("heading").and_(page.get_by_text("product 1"))
可以定位到<h3>Product 1</h3>
or_
- 1.33以上版本才支持
- 满足两个定位器之中一个, 如果两个均匹配到,但是不是同一个元素会报 multiple elements
page.get_by_role("heading").and_(page.get_by_text("product 1"))
可以定位到<h3>Product 1</h3>
查找一个元素的父元素
page.get_by_text("product 1").locator("..")
定位到文本是product 1的元素的父元素
iframe定位
如果要定位iframe中的元素, 可以先page.frame_locator("my-frame")
定位到iframe,再定位到具体的元素