菜单
开源 本页面内容适用于开源版本。

page.$$(selector)

警告

尽可能使用基于 locator 的 page.locator(selector) 代替。

然而,在使用列表或表格中的元素时,使用 locator 可能并非总是有效,特别是当无法可靠地持续识别单个元素(例如,由于属性变化或非唯一性)时。在这种情况下, $$ 仍然很有用。

该方法查找页面中匹配指定选择器的所有元素。如果没有元素匹配选择器,返回值解析为 []。当您想检索元素列表并遍历它们以查找测试用例所需的元素时,这尤其有用。

返回值

类型描述
Promise<ElementHandle[]>一个 Promise,当找到匹配元素时,它会返回选择器的 ElementHandle 数组。

示例

JavaScript
import { browser } from 'k6/browser';

export const options = {
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
};

export default async function () {
  const page = await browser.newPage();

  await page.goto('https://test.k6.io/');

  // Retrieve all the td elements.
  const cells = await page.$$('td');
  for (let i = 0; i < cells.length; i++) {
    if ((await cells[i].innerText()) == '/pi.php?decimals=3') {
      // When the element is found, click on it and
      // wait for the navigation.
      await Promise.all([page.waitForNavigation(), cells[i].click()]);
      break;
    }
  }

  // Wait for an important element to load.
  await page.locator('//pre[text()="3.141"]').waitFor();
}