如何在 Playwright 测试中获取元素的属性?

Dev*_*Dev 21 javascript playwright

我正在尝试在测试中获取元素的属性。我的测试如下所示:

test(`Should be at least 5 characters long`, async({ page }) => {
  await page.goto('http://localhost:8080');
  const field = await page.locator('id=emailAddress');

  const _attribute = await field.getAttribute('minlength');
  const minlength = Number(_attribute);

  await expect(minlength).toBeGreaterThanOrEqual(5);    
});
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我可以看到该minlength值为0。这是因为_attributenull。但是,我不明白为什么。field是一个Locator. 但是,我似乎无法获取该属性或其值。我究竟做错了什么?

小智 28

这是相同的,但使用本机 PlayWright 函数来获取属性值

const inputElement = page.locator('#emailAddress');
const minLength = await inputElement.getAttribute('minLength');
Run Code Online (Sandbox Code Playgroud)


typ*_*ris 8

以下内容对我有用

const inputElement = page.locator('#emailAddress');
minLength = await inputElement.evaluate(e => (e as HTMLInputElement).minLength);
Run Code Online (Sandbox Code Playgroud)