How to open Playwright Test generator in Java and generate/inpect locators.
Precondition- Maven has to be configured.
First step is open the terminal of an IntelliJ project:
Then in terminal type below command to Playwright Codegen.
Command explanation
The mvn exec:java command tells Maven to run the Java code in the current directorory.
The -e option tells Maven to print error messages to the console if there are any.
-D exec.mainClass=com.microsoft.playwright.CLI option tells Maven to run the CLI class in the com.microsoft.playwright package.
-D exec.args=”codegen demo.playwright.dev/todomvc” option tells Maven to pass the codegen command and the URL of the TodoMVC demo app to the CLI class.
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="codegen demo.playwright.dev/todomvc"
This https://playwright.dev/todomvc was given there without https:// part.
In my case I uses https://blazedemo.com/login so command is changed as
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="codegen blazedemo.com/login"
It will open a browser window along with the code gen. Perform your actions and they will be captured. (Here you can’t add assertions but click on the element so it get recorded and later you can change it to an assertion while modifying the code.
You can change the language type also has an option to pause and resume
Once you done recording , copy the code from it and close the genertor and browser.
So I got below code.
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import java.util.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(false));
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://blazedemo.com/login");
page.getByLabel("E-Mail Address").click();
page.getByLabel("E-Mail Address").fill("emailaressvalue");
page.getByLabel("Password").click();
page.getByLabel("Password").fill("myasswrod");
page.getByLabel("Remember Me").check();
page.locator("html").click();
}
}
}
To generate the locators “quoting official guide”
You can generate locators with the test generator.
Press the ‘Record’ button to stop the recording and the ‘Pick Locator’ button will appear.
Click on the ‘Pick Locator’ button and then hover over elements in the browser window to see the locator highlighted underneath each element.
To choose a locator click on the element you would like to locate and the code for that locator will appear in the field next to the Pick Locator button.
You can then edit the locator in this field to fine tune it or use the copy button to copy it and paste it into your code.