13

I have input text field on the page with id "email30" and I am trying to read it's value from Playwright

  let dd_handle = await page.$("#email30");
  let value = await dd_handle.getAttribute("value");

However it come back "" although I have a value inside the input text. When I inspect I don't see the value attribute is set to a current value either.

Normal JS code as following gives me correct value

document.getElementById("email30").value

Not sure how I can read value from the playwright framework. Can any one please advise? Their documents are quite not helpful here.

Paresh Varde
  • 1,025
  • 3
  • 14
  • 37

3 Answers3

19

There are three major trends how to retrieve input values with playwright/puppeteer.

page.evaluate

const value = await page.evaluate(el => el.value, await page.$('input'))

page.$eval

const value = await page.$eval('input', el => el.value)

page.evaluate with Element.getAttribute

const value = await page.evaluate(() => document.querySelector('input').getAttribute('value'))

The first two will return the same result with very similar performance, I can't bring up an example when we could favor one over the other (maybe one: the one with $eval is shorter). The third one with Element.getAttribute is not advised if you are manipulating an input's value before evaluation and you want to retrieve the new value. It will always return the original attribute value, which is an empty string in most of the cases. It is a topic of attribute vs property value in JavaScript.

However page.evaluate with Element.getAttribute can be handy when you need such attributes that can't be accessed with the other mentioned methods (e.g.: class names, data attributes, aria attributes etc.)

theDavidBarton
  • 5,676
  • 3
  • 16
  • 40
7

Ok finally following code did the job for me!

const value = await page.$eval("#email30", (el) => el.value);
Paresh Varde
  • 1,025
  • 3
  • 14
  • 37
1

This works the best so far

const somevalue = this.page.inputValue('#Name');
QA Fortify
  • 31
  • 6
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Dec 07 '21 at 21:29