选择正确的行并单击复选框

问题描述 投票:0回答:2

我是剧作家新手,不知道如何处理这个问题。我有一个包含数据的表,每行的第一列都有一个复选框。我希望能够选择正确的行来单击复选框。我不确定如何获得该行。

我的桌子:

|    |  ID   |  Name        | Phone
| [] | 3745  | Frank Smith  | 485-555-9394
| [] | 9394  | Joe Johnson  | 384-555-2332

在 HTML 中:

<table>
  <thead>
  <tr>
    <th></th>
    <th>ID</th>
    <th>Name</th>
    <th>Phone</th>
  </tr>
  </thead>
  <tbody>
  <tr role="row" class="odd">
    <td><input type="checkbox" name="personid"></td>
    <td>3745</td>
    <td>Frank Smith</td>
    <td>485-555-9394</td>
  </tr>
  <tr role="row" class="even">
    <td><input type="checkbox" name="personid"></td>
    <td>9394</td>
    <td>Joe Johnson</td>
    <td>384-555-2332</td>
  </tr>
  </tbody>
</table>

现在,我想选中与用户 ID 9394 关联的复选框。

我原来的解决方案是(在nodejs中):

page.locator('table tbody tr': {hasText: '9394'}.locator('td').nth(0).locator('input').check();

但是,正如您在上面的示例中看到的,它将选择电话号码以 9394 结尾的行,否则会给我一个错误,因为它返回多行。

我的另一个想法是做类似的事情:

page.locator('table tbody tr td:nth(1)', {hasText: '9394'}). ???

我只是不确定如何返回到该行中的上一个

td input
以单击复选框。

playwright
2个回答
1
投票

除了使用

hasText
,您还可以定义元素必须包含的子定位器并使用
has
引用它。

假设id始终在第二列,则可以使用以下代码:

const idLocator = page.locator('td:nth-child(2)', { hasText: '9394' });
const checkbox = page.locator('table tbody tr', { has: idLocator }).locator('input[type=checkbox]');
await checkbox.check();

0
投票

定位行最简单的方法是将行用作 aria 角色

page.getByRole('row')

并通过单元格的文本过滤它

.filter({ hasText: '9394' })

一起:

page.getByRole('row').filter({ hasText: '9394' })

最后,找到该行中的复选框并将其链接起来

page.getByRole('row').filter({ hasText: '9394' }).getByRole('checkbox')

查看文档 https://playwright.dev/docs/next/api/class-framelocator#frame-locator-get-by-role

© www.soinside.com 2019 - 2024. All rights reserved.