In this short tutorial, we will see how to do browser automation with a Java equivalent of JavaScript Puppeteer: a new framework developed by Microsoft called Playwright.
1) Import the dependency in your pom.xml
In your pom.xml file, add:
<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.15.2</version> </dependency>
2) Open Firefox and navigate to Wikipedia.com
To open a Firefox browser and navigate to Wikipedia.com (without Headless mode), simply run:
package com;
import com.microsoft.playwright.*;
public class PlayWrightBlog {
public static void main(String[] args) {
Playwright playwright = Playwright.create();
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
options.setHeadless(false);
Browser browser = playwright.firefox().launch(options);
Page page = browser.newPage();
page.navigate("https://www.wikipedia.com");
}
}
3) Open Chrome and navigate to Wikipedia.com
To open a Chrome browser and navigate to Wikipedia.com, simply change the browser creation line from above:
package com;
import com.microsoft.playwright.*;
public class PlayWrightBlog {
public static void main(String[] args) {
Playwright playwright = Playwright.create();
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
options.setHeadless(false);
Browser browser = playwright.chromium().launch(options);
Page page = browser.newPage();
page.navigate("https://www.wikipedia.com");
}
}
That’s it for this tutorial ! If you have any question, please leave a reply below, we answer within 24h.