playwright元素定位

元素定位

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

通过 cssxpath获取,比如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,再定位到具体的元素

  • 24
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值