经过多天对微软自动化框架Playwright的使用,发现还没有讲该框架的常用方法,比如定位、按键等操作使用。今天我们正好来说说。
一、鼠标类操作
1.单点
.click();
click(String selector) {
this.click(selector, (ClickOptions)null); }
2.双击
.dbclick();
dblclick(String selector) {
this.dblclick(selector, (DblclickOptions)null); }
3.鼠标左键
page.click(new Locator.ClickOptions().setButton(MouseButton.LEFT).toString());
4.鼠标右键
page.click(new Locator.ClickOptions().setButton(MouseButton.RIGHT).toString());
5.Shift+单点
page.click(new Locator.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.SHIFT)).toString());
6.鼠标悬浮
page.hover();
7.左上角点击
page.click(new Locator.ClickOptions().setPosition(0,0).toString());
8.强制点击(如果有覆盖物,如活动弹窗等,在元素上产生干扰)
page.click(new Locator.ClickOptions().setForce(true).toString());
9.下发事件(没有通过常规点击方式)
page.getByRole(AriaRole.BUTTON).dispatchEvent("click");
二、键盘输入
1.字符串批量
page.locator("#area").type("Hello,world!");
2.键盘字符输入
page.getByText("Submit").press("Enter");
page.getByRole(AriaRole.TEXTBOX).press("Control+ArrowRight");
page.getByRole(AriaRole.TEXTBOX).press("$");
3.大小写区分,支持快捷键组合方式
page.locator("#name").press("Shift+A");
page.locator("#name").press("Shift+ArrowLeft");
将Playwright对浏览器的操作代码记录并解释下
- 创建浏览器对象
//默认为无头浏览器方式启动
browser = playwright.chromium().launch();
//浏览器参数设定方式启动
browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true).setSlowMo(5000))
;
2.创建浏览器上下文
context = browser.newContext
3.创建page对象
一个page对应一个浏览器选项卡
page = context.newPage();
4.多个浏览器启动
package org.example;import com.microsoft.playwright.Browser;import com.microsoft.playwright.BrowserType;import com.microsoft.playwright.Playwright;public class MoreBrowserDemo {
public Browser createBrowser(String name, Playwright playwright) {
try{
switch (name){
case "firefox":
return playwright.firefox().launch(new BrowserType.LaunchOptions().setHeadless(false).setTimeout(120*1000)); "chromium":
return playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setTimeout(120*1000)); "webkit":
return playwright.webkit().launch(); }
}catch (Exception e){
e.printStackTrace(); }
return null; }
}
这样就可以根据不同的浏览器对应启动方法,大家可以写代码自己尝试下。
标签:playwright,java,ClickOptions,click,Playwright,UI,new,浏览器,page From: https://blog.51cto.com/u_11894/6410444