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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With