Playwright 实现流程自动化,以及自动获取操作记录代码
Playwright 实现流程自动化,以及自动获取操作记录代码
引入pom
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.42.0</version>
</dependency>
具体代码
package git.jiang;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.WaitForSelectorState;
import java.util.regex.Pattern;
public class DifyAutoLogin {
public static void main(String[] args) {
// 设置镜像源以加速浏览器下载
System.setProperty("PLAYWRIGHT_DOWNLOAD_HOST", "https://npmmirror.com/mirrors/playwright-browser/");
try (Playwright playwright = Playwright.create()) {
// 1. 启动浏览器(默认Chromium)
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions()
.setHeadless(false)
.setSlowMo(1000)
);
// 创建支持忽略 HTTPS 错误的浏览器上下文
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setIgnoreHTTPSErrors(true)
.setViewportSize(1280, 720));
Page page = context.newPage();
// 2. 打开登录页
page.navigate("http://127.0.0.1/");
// 3. 找到 ID 为 email 输入
page.locator("#email").fill("admin");
// 3. 找到 ID 为 password 输入
page.locator("#password").fill("123456");
// 找到登录按钮点击登录
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("登录")).click();
// 等待页面加载完成
page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("探索")).click();
page.locator("div").filter(new Locator.FilterOptions().setHasText(Pattern.compile("^小秘$"))).nth(1).click();
page.getByPlaceholder("和 小秘 聊天").click();
page.getByPlaceholder("和 小秘 聊天").fill("你好");
page.locator(".flex > .btn").click();
// 保持浏览器打开(调试用,可以自动获取页面操作转换为实现代码)
System.out.println("操作成功!");
page.pause();
}
}
}

浙公网安备 33010602011771号