在 Playwright 中获取输入元素的值

Jak*_*eDK 4 playwright

我如何返回 elem 的值,以便我可以验证它是真的1

const elem = await page.$('input#my-input')
await elem.fill('1')
Run Code Online (Sandbox Code Playgroud)

Max*_*itt 6

最简单的方法是使用$eval. 在这里你会看到一个小例子:

const playwright = require("playwright");

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.setContent(`<input id="foo"/>`);
  await page.type("#foo", "New value")
  console.log(await page.$eval("#foo", el => el.value))
  await page.screenshot({ path: `example.png` });
  await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,[`$eval()`不会执行可操作性检查](https://playwright.dev/docs/actionability)(它不会自动等待),因此您可能需要在`$eval()之前执行` 类似 `await page.waitForSelector("#foo")` (2认同)
  • 如果遇到类型问题,您可以设置:`el as HTMLInputElement;` (2认同)

Yev*_*kov 5

inputValue Playwright v1.13.0 添加了方法

await page.inputValue('input#my-input');
Run Code Online (Sandbox Code Playgroud)

input.value为选定的<input><textarea>元素返回。抛出非输入元素。阅读更多

  • 比 `$eval()` 更好。谢谢! (3认同)

Gaj*_*ije 5

从版本 1.19(可能还有更低版本)开始,不推荐使用 Element Handler。而不是使用定位器。

page.locator(selector).innerText()
Run Code Online (Sandbox Code Playgroud)

在你的情况下断言它将是

expect(page.locator("input#my-input").innerText().includes("1")).toBeTruthy()
Run Code Online (Sandbox Code Playgroud)

了解更多信息: https ://playwright.dev/docs/api/class-elementhandle#element-handle-fill