3

Hello Playwright experts,

I have this input field

<input id="myName" placeholder="e.g. Max" maxlength="15" class="xyz"/>

I have tried this JAVA code:

page.locator("[placeholder=\"e.g. Max\"]").textContent();

It does not work :-( but I can fill

page.locator("[placeholder=\"e.g. Max\"]").fill("Loren"); // this works

Could you help and has an idea?

Thank you in advance.

Cheers Loren

hardkoded
  • 18,915
  • 3
  • 52
  • 64
lorenlai
  • 51
  • 7

4 Answers4

6

textContext won't return a value of an input. The same will happen if you try that in the DevTools.
You can use inputValue instead.
e.g.

page.locator("#myName").inputValue();
hardkoded
  • 18,915
  • 3
  • 52
  • 64
2

In case you want to assert your value you can use the .hasValue assertion. You can read more about it from the playwright docs.

assertThat(page.locator("#myName")).hasValue("input-value");
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • wowww, so many possibilities to this issue. :-) Thank you very much. I have learnt something new :-) – lorenlai Jul 01 '22 at 05:44
2

You could also use the imho more generic getAttribute:

page.locator("#myName").getAttribute("placeholder");

Documentation: https://playwright.dev/docs/api/class-locator#locator-get-attribute

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
0

Theory is that

inputValue() is used to retrieve the value of input elements that you just typed.

textContent() is a method that is used to get the visible text content of an element on a web page. it can be a header tag. This method is useful for web scraping and verifying the content of a page.

Here is a code example

page.navigate("https://the-internet.herokuapp.com/forgot_password");
Locator inputTextField=page.locator("//input[@id='email']");


// Get input text of an element using inputValue();
String actualInputVal=inputTextField.inputValue();
System.out.println("actualInputVal=="+actualInputVal);
// Assert the value of it using  hasValue
assertThat(inputTextField).hasValue("My input");


Locator forgetPasswordHeader=page.locator("//h2[text()='Forgot Password']");
String forgetPasswordHeaderActualText=forgetPasswordHeader.textContent();
System.out.println("forgetPasswordHeaderActualText=="+forgetPasswordHeaderActualText);
// you can't use hasValue here since  it's not an input element so use hasText
assertThat(forgetPasswordHeader).hasText("Forgot Password");

This will print

actualInputVal==My input
forgetPasswordHeaderActualText==Forgot Password
Sameera De Silva
  • 1,722
  • 1
  • 22
  • 41