Page
页面提供了与[浏览器]中的单个标签页或Chromium中的扩展后台页面进行交互的方法。一个[浏览器]实例可能有多个[页面]实例。
🌐 Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.
此示例创建一个页面,将其导航到 URL,然后保存屏幕截图:
🌐 This example creates a page, navigates it to a URL, and then saves a screenshot:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
browser.close();
}
}
}
Page 类会触发各种事件(如下所述),可以使用 Node 的任何原生 EventEmitter 方法来处理这些事件,例如 on、once 或 removeListener。
🌐 The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.
此示例会记录单个页面 load 事件的消息:
🌐 This example logs a message for a single page load event:
page.onLoad(p -> System.out.println("Page loaded!"));
要取消订阅事件,请使用 removeListener 方法:
🌐 To unsubscribe from events use the removeListener method:
Consumer<Request> logRequest = interceptedRequest -> {
System.out.println("A request was made: " + interceptedRequest.url());
};
page.onRequest(logRequest);
// Sometime later...
page.offRequest(logRequest);
方法
🌐 Methods
addInitScript
Added before v1.9添加将在以下场景之一进行评估的脚本:
🌐 Adds a script which would be evaluated in one of the following scenarios:
- 每当导航页面时。
- 每当子框架被附加或导航时。在这种情况下,脚本会在新附加的框架上下文中执行。
脚本在文档创建后但在其任何脚本运行之前进行评估。这对于修改 JavaScript 环境非常有用,例如,用于初始化 Math.random。
🌐 The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.
用法
在页面加载之前重写 Math.random 的示例:
🌐 An example of overriding Math.random before the page loads:
// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory
page.addInitScript(Paths.get("./preload.js"));
通过 BrowserContext.addInitScript() 和 Page.addInitScript() 安装的多个脚本的执行顺序未定义。
参数
返回
addLocatorHandler
Added in: v1.42在测试网页时,有时会出现意外的覆盖层,例如“注册”对话框,这会阻挡你想要自动化的操作,例如点击按钮。这些覆盖层并不总是以相同的方式或在相同的时间出现,使得在自动化测试中处理它们变得棘手。
🌐 When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.
这种方法允许你设置一个特殊的功能,称为处理程序,当检测到覆盖层可见时会激活。处理程序的工作是移除覆盖层,从而让你的测试像覆盖层不存在一样继续进行。
🌐 This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
要记住的事情:
🌐 Things to keep in mind:
- 当叠加层按预期显示时,我们建议在测试中明确等待它,并将其作为正常测试流程的一部分来关闭,而不是使用 Page.addLocatorHandler()。
- 在执行或重试需要进行可操作性检查的操作之前,或者在执行自动等待断言检查之前,Playwright 会每次检查覆盖层是否存在。当覆盖层可见时,Playwright 会先调用处理程序,然后再继续执行操作或断言。请注意,只有在执行操作或断言时才会调用该处理程序——如果覆盖层变为可见但你没有执行任何操作,处理程序将不会被触发。
- 在执行处理程序后,Playwright 将确保触发该处理程序的覆盖层不再可见。你可以通过 setNoWaitAfter 选择退出此行为。
- 处理程序的执行时间计入执行该处理程序的动作/断言的超时。如果你的处理程序运行时间过长,可能会导致超时。
- 你可以注册多个处理程序,但同一时间只会运行一个处理程序。确保处理程序中的操作不依赖于其他处理程序。
运行处理程序会在测试中途更改页面状态。例如,它会更改当前聚焦的元素并移动鼠标。确保在处理程序之后执行的操作是自包含的,并且不依赖于焦点和鼠标状态保持不变。
🌐 Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
例如,考虑一个测试,它首先调用 Locator.focus(),然后调用 Keyboard.press()。如果你的处理程序在这两个操作之间点击了一个按钮,被聚焦的元素很可能会错误,并且按键操作将发生在意外的元素上。为避免此问题,请改为使用 Locator.press()。
🌐 For example, consider a test that calls Locator.focus() followed by Keyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. Use Locator.press() instead to avoid this problem.
另一个例子是一系列鼠标操作,其中 Mouse.move() 后跟 Mouse.down()。同样,当处理程序在这两个操作之间运行时,鼠标按下时的位置将不正确。建议使用像 Locator.click() 这样的自包含操作,而不是依赖处理程序未改变的状态。
🌐 Another example is a series of mouse actions, where Mouse.move() is followed by Mouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions like Locator.click() that do not rely on the state being unchanged by a handler.
用法
一个在“注册新闻通讯”对话框出现时将其关闭的示例:
🌐 An example that closes a "Sign up to the newsletter" dialog when it appears:
// Setup the handler.
page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () -> {
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click();
});
// Write the test as usual.
page.navigate("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
一个在显示“确认你的安全详情”页面时跳过该页面的示例:
🌐 An example that skips the "Confirm your security details" page when it is shown:
// Setup the handler.
page.addLocatorHandler(page.getByText("Confirm your security details"), () -> {
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click();
});
// Write the test as usual.
page.navigate("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
这是一个在每次可操作性检查时使用自定义回调的示例。它使用一个始终可见的 <body> 定位器,因此在每次可操作性检查之前都会调用该处理程序。重要的是要指定 setNoWaitAfter,因为该处理程序不会隐藏 <body> 元素。
🌐 An example with a custom callback on every actionability check. It uses a <body> locator that is always visible, so the handler is called before every actionability check. It is important to specify setNoWaitAfter, because the handler does not hide the <body> element.
// Setup the handler.
page.addLocatorHandler(page.locator("body"), () -> {
page.evaluate("window.removeObstructionsForTestIfNeeded()");
}, new Page.AddLocatorHandlerOptions().setNoWaitAfter(true));
// Write the test as usual.
page.navigate("https://example.com");
page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();
处理器以原始定位器作为参数。你还可以通过设置 setTimes 在多次调用后自动移除处理器:
🌐 Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting setTimes:
page.addLocatorHandler(page.getByLabel("Close"), locator -> {
locator.click();
}, new Page.AddLocatorHandlerOptions().setTimes(1));
参数
-
触发处理程序的定位器。
-
当 locator 出现时应运行的函数。该函数应移除阻碍点击等操作的元素。
-
optionsPage.AddLocatorHandlerOptions(optional)
返回
addScriptTag
Added before v1.9在页面中添加一个带有所需 URL 或内容的 <script> 标签。当脚本加载完成或脚本内容被注入到框架中时,返回添加的标签。
🌐 Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.
用法
Page.addScriptTag();
Page.addScriptTag(options);
参数
optionsPage.AddScriptTagOptions(optional)
返回
addStyleTag
Added before v1.9将一个带有目标 URL 的 <link rel="stylesheet"> 标签或带有内容的 <style type="text/css"> 标签添加到页面中。当样式表的 onload 触发,或 CSS 内容被注入到框架中时,会返回添加的标签。
🌐 Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
用法
Page.addStyleTag();
Page.addStyleTag(options);
参数
optionsPage.AddStyleTagOptions(optional)
返回
bringToFront
Added before v1.9将页面置于前面(激活选项卡)。
🌐 Brings page to front (activates tab).
用法
Page.bringToFront();
返回
close
Added before v1.9如果 setRunBeforeUnload 是 false,则不会执行任何卸载处理程序,并会等待页面关闭。如果 setRunBeforeUnload 是 true,该方法会运行卸载处理程序,但不会等待页面关闭。
🌐 If setRunBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If setRunBeforeUnload is true the method will run unload handlers, but will not wait for the page to close.
默认情况下,page.close() 不会 运行 beforeunload 处理程序。
🌐 By default, page.close() does not run beforeunload handlers.
如果 setRunBeforeUnload 被设置为 true,可能会弹出一个 beforeunload 对话框,并且应通过 Page.onDialog(handler) 事件手动处理。
🌐 if setRunBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via Page.onDialog(handler) event.
用法
Page.close();
Page.close(options);
参数
optionsPage.CloseOptions(optional)-
setReasonString (optional) Added in: v1.40#报告因页面关闭而中断的操作的原因。
-
setRunBeforeUnloadboolean (optional)#默认为
false。是否运行 before unload 页面处理程序。
-
返回
consoleMessages
Added in: v1.56返回该页面最近的(当前最多)200条控制台消息。更多详情请参阅 Page.onConsoleMessage(handler)。
🌐 Returns up to (currently) 200 last console messages from this page. See Page.onConsoleMessage(handler) for more details.
用法
Page.consoleMessages();
返回
content
Added before v1.9获取页面的完整 HTML 内容,包括文档类型。
🌐 Gets the full HTML contents of the page, including the doctype.
用法
Page.content();
返回
context
Added before v1.9获取页面所属的浏览器上下文。
🌐 Get the browser context that the page belongs to.
用法
Page.context();
返回
dragAndDrop
Added in: v1.13此方法将源元素拖动到目标元素。它会先移动到源元素,执行一个 mousedown,然后移动到目标元素并执行一个 mouseup。
🌐 This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.
用法
page.dragAndDrop("#source", "#target");
// or specify exact positions relative to the top-left corners of the elements:
page.dragAndDrop("#source", "#target", new Page.DragAndDropOptions()
.setSourcePosition(34, 7).setTargetPosition(10, 20));
参数
-
用于搜索要拖动的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
用于搜索要放置的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
optionsPage.DragAndDropOptions(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setSourcePositionSourcePosition (optional) Added in: v1.14#在此位置点击源元素,相对于元素内边距框的左上角。如果未指定,则使用元素的某个可见点。
-
setStepsint (optional) Added in: v1.57#默认为 1。发送
n个插值的mousemove事件以表示拖动的mousedown和mouseup之间的移动。当设置为 1 时,在目标位置仅触发一个mousemove事件。 -
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
setTargetPositionTargetPosition (optional) Added in: v1.14#在此点相对于元素填充框左上角投放目标元素。如果未指定,则使用元素的某个可见点。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
emulateMedia
Added before v1.9此方法通过 colorScheme 参数更改 CSS media type 到 media 参数和/或 'prefers-colors-scheme' 媒体特性。
🌐 This method changes the CSS media type through the media argument, and/or the 'prefers-colors-scheme' media feature, using the colorScheme argument.
用法
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
page.evaluate("() => matchMedia('screen').matches");
// → false
page.evaluate("() => matchMedia('print').matches");
// → true
page.emulateMedia(new Page.EmulateMediaOptions());
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
// → true
page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
// → false
参数
optionsPage.EmulateMediaOptions(optional)-
setColorSchemenull |enum ColorScheme { LIGHT, DARK, NO_PREFERENCE }(optional) Added in: v1.9#模拟 prefers-colors-scheme 媒体特性,支持的值为
'light'和'dark'。传入null可禁用配色方案模拟。'no-preference'已被弃用。 -
setContrastnull |enum Contrast { NO_PREFERENCE, MORE }(optional) Added in: v1.51#模拟
'prefers-contrast'媒体特性,支持的值有'no-preference'、'more'。传入null可禁用对比度模拟。 -
setForcedColorsnull |enum ForcedColors { ACTIVE, NONE }(optional) Added in: v1.15#模拟
'forced-colors'媒体特性,支持的值为'active'和'none'。传递null可禁用强制颜色模拟。 -
setMedianull |enum Media { SCREEN, PRINT }(optional) Added in: v1.9#更改页面的 CSS 媒体类型。唯一允许的值是
'screen'、'print'和null。传递null会禁用 CSS 媒体模拟。 -
setReducedMotionnull |enum ReducedMotion { REDUCE, NO_PREFERENCE }(optional) Added in: v1.12#模拟
'prefers-reduced-motion'媒体特性,支持的值有'reduce'、'no-preference'。传入null会禁用减小动画模拟。
-
返回
evaluate
Added before v1.9返回 expression 调用的值。
🌐 Returns the value of the expression invocation.
如果传递给 Page.evaluate() 的函数返回一个 Promise,那么 Page.evaluate() 将会等待该 promise 被解析并返回它的值。
🌐 If the function passed to the Page.evaluate() returns a Promise, then Page.evaluate() would wait for the promise to resolve and return its value.
如果传递给 Page.evaluate() 的函数返回一个非 Serializable 值,那么 Page.evaluate() 将解析为 undefined。Playwright 还支持传输一些 JSON 无法序列化的其他值:-0、NaN、Infinity、-Infinity。
🌐 If the function passed to the Page.evaluate() returns a non-Serializable value, then Page.evaluate() resolves to undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.
用法
将参数传递给 expression :
🌐 Passing argument to expression:
Object result = page.evaluate("([x, y]) => {\n" +
" return Promise.resolve(x * y);\n" +
"}", Arrays.asList(7, 8));
System.out.println(result); // prints "56"
也可以传入字符串而不是函数:
🌐 A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"
ElementHandle 实例可以作为参数传递给 Page.evaluate():
ElementHandle bodyHandle = page.evaluate("document.body");
String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello"));
bodyHandle.dispose();
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
evaluateHandle
Added before v1.9以 JSHandle 的形式返回 expression 调用的值。
🌐 Returns the value of the expression invocation as a JSHandle.
Page.evaluate() 和 Page.evaluateHandle() 唯一的区别是 Page.evaluateHandle() 返回 JSHandle。
🌐 The only difference between Page.evaluate() and Page.evaluateHandle() is that Page.evaluateHandle() returns JSHandle.
如果传递给 Page.evaluateHandle() 的函数返回一个 Promise,那么 Page.evaluateHandle() 会等待该 promise 解决并返回其值。
🌐 If the function passed to the Page.evaluateHandle() returns a Promise, then Page.evaluateHandle() would wait for the promise to resolve and return its value.
用法
// Handle for the window object.
JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");
也可以传入字符串而不是函数:
🌐 A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".
JSHandle 实例可以作为参数传递给 Page.evaluateHandle():
JSHandle aHandle = page.evaluateHandle("() => document.body");
JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello"));
System.out.println(resultHandle.jsonValue());
resultHandle.dispose();
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
exposeBinding
Added before v1.9该方法在此页面每一帧的 window 对象上添加了一个名为 name 的函数。调用该函数时,会执行 callback 并返回一个 Promise,该 Promise 会解析为 callback 的返回值。如果 callback 返回一个 Promise,则会等待其完成。
🌐 The method adds a function called name on the window object of every frame in this page. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.
callback 函数的第一个参数包含关于调用者的信息:{ browserContext: BrowserContext, page: Page, frame: Frame }。
🌐 The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.
有关上下文范围版本,请参见 BrowserContext.exposeBinding()。
🌐 See BrowserContext.exposeBinding() for the context-wide version.
通过 Page.exposeBinding() 安装的函数在页面导航后仍然有效。
🌐 Functions installed via Page.exposeBinding() survive navigations.
用法
向页面中的所有框架公开页面 URL 的示例:
🌐 An example of exposing page URL to all frames in a page:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.exposeBinding("pageURL", (source, args) -> source.page().url());
page.setContent("<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.pageURL();\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>");
page.click("button");
}
}
}
参数
-
窗口对象上的函数名称。
-
callbackBindingCallback#将在 Playwright 上下文中调用的回调函数。
-
optionsPage.ExposeBindingOptions(optional)
返回
exposeFunction
Added before v1.9该方法在页面每个帧的 window 对象上添加了一个名为 name 的函数。调用该函数时,会执行 callback,并返回一个 Promise,该 Promise 解析为 callback 的返回值。
🌐 The method adds a function called name on the window object of every frame in the page. When called, the function executes callback and returns a Promise which resolves to the return value of callback.
如果 callback 返回一个 Promise,它将被等待。
🌐 If the callback returns a Promise, it will be awaited.
有关上下文范围内暴露的函数,请参阅 BrowserContext.exposeFunction()。
🌐 See BrowserContext.exposeFunction() for context-wide exposed function.
通过 Page.exposeFunction() 安装的函数在页面导航后仍然存在。
🌐 Functions installed via Page.exposeFunction() survive navigations.
用法
在页面中添加 sha256 函数的示例:
🌐 An example of adding a sha256 function to the page:
import com.microsoft.playwright.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.exposeFunction("sha256", args -> {
try {
String text = (String) args[0];
MessageDigest crypto = MessageDigest.getInstance("SHA-256");
byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(token);
} catch (NoSuchAlgorithmException e) {
return null;
}
});
page.setContent(
"<script>\n" +
" async function onClick() {\n" +
" document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
" }\n" +
"</script>\n" +
"<button onclick=\"onClick()\">Click me</button>\n" +
"<div></div>"
);
page.click("button");
}
}
}
参数
返回
frame
Added before v1.9返回符合指定条件的帧。必须指定 name 或 url。
🌐 Returns frame matching the specified criteria. Either name or url must be specified.
用法
Frame frame = page.frame("frame-name");
Frame frame = page.frameByUrl(Pattern.compile(".*domain.*"));
参数
返回
frameByUrl
Added in: v1.9返回具有匹配 URL 的框架。
🌐 Returns frame with matching URL.
用法
Page.frameByUrl(url);
参数
返回
frameLocator
Added in: v1.17使用 iframe 时,你可以创建一个框架定位器,该定位器将进入 iframe 并允许选择该 iframe 中的元素。
🌐 When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.
用法
以下代码片段用于在 id 为 my-frame 的 iframe 中查找文本为“Submit”的元素,如同 <iframe id="my-frame"> 一样:
🌐 Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:
Locator locator = page.frameLocator("#my-iframe").getByText("Submit");
locator.click();
参数
返回
frames
Added before v1.9附加到页面的所有框架的数组。
🌐 An array of all frames attached to the page.
用法
Page.frames();
返回
getByAltText
Added in: v1.27允许通过替代文本定位元素。
🌐 Allows locating elements by their alt text.
用法
例如,此方法将通过替代文本“Playwright logo”来查找图片:
🌐 For example, this method will find the image by alt text "Playwright logo":
<img alt='Playwright logo'>
page.getByAltText("Playwright logo").click();
参数
-
用于定位元素的文本。
-
optionsPage.GetByAltTextOptions(optional)
返回
getByLabel
Added in: v1.27允许通过关联的 <label> 或 aria-labelledby 元素的文本,或通过 aria-label 属性来定位输入元素。
🌐 Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.
用法
例如,这种方法将在以下 DOM 中根据标签“用户名”和“密码”查找输入项:
🌐 For example, this method will find inputs by label "Username" and "Password" in the following DOM:
<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
page.getByLabel("Username").fill("john");
page.getByLabel("Password").fill("secret");
参数
-
用于定位元素的文本。
-
optionsPage.GetByLabelOptions(optional)
返回
getByPlaceholder
Added in: v1.27允许通过占位符文本定位输入元素。
🌐 Allows locating input elements by the placeholder text.
用法
例如,考虑以下 DOM 结构。
🌐 For example, consider the following DOM structure.
<input type="email" placeholder="name@example.com" />
你可以在通过占位符文本找到输入后填充输入:
🌐 You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
参数
-
用于定位元素的文本。
-
optionsPage.GetByPlaceholderOptions(optional)
返回
getByRole
Added in: v1.27允许通过元素的ARIA 角色、ARIA 属性和可访问名称来定位元素。
🌐 Allows locating elements by their ARIA role, ARIA attributes and accessible name.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>
你可以通过每个元素的隐式角色来定位它:
🌐 You can locate each element by it's implicit role:
assertThat(page
.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Sign up")))
.isVisible();
page.getByRole(AriaRole.CHECKBOX,
new Page.GetByRoleOptions().setName("Subscribe"))
.check();
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName(
Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
.click();
参数
-
roleenum AriaRole { ALERT, ALERTDIALOG, APPLICATION, ARTICLE, BANNER, BLOCKQUOTE, BUTTON, CAPTION, CELL, CHECKBOX, CODE, COLUMNHEADER, COMBOBOX, COMPLEMENTARY, CONTENTINFO, DEFINITION, DELETION, DIALOG, DIRECTORY, DOCUMENT, EMPHASIS, FEED, FIGURE, FORM, GENERIC, GRID, GRIDCELL, GROUP, HEADING, IMG, INSERTION, LINK, LIST, LISTBOX, LISTITEM, LOG, MAIN, MARQUEE, MATH, METER, MENU, MENUBAR, MENUITEM, MENUITEMCHECKBOX, MENUITEMRADIO, NAVIGATION, NONE, NOTE, OPTION, PARAGRAPH, PRESENTATION, PROGRESSBAR, RADIO, RADIOGROUP, REGION, ROW, ROWGROUP, ROWHEADER, SCROLLBAR, SEARCH, SEARCHBOX, SEPARATOR, SLIDER, SPINBUTTON, STATUS, STRONG, SUBSCRIPT, SUPERSCRIPT, SWITCH, TAB, TABLE, TABLIST, TABPANEL, TERM, TEXTBOX, TIME, TIMER, TOOLBAR, TOOLTIP, TREE, TREEGRID, TREEITEM }#所需的咏叹调角色。
-
optionsPage.GetByRoleOptions(optional)-
setCheckedboolean (optional)#通常由
aria-checked或原生<input type=checkbox>控件设置的属性。了解更多关于
aria-checked的信息。 -
setDisabledboolean (optional)#通常由
aria-disabled或disabled设置的属性。note与大多数其他属性不同,
disabled是通过 DOM 层级继承的。了解更多关于aria-disabled的信息。 -
setExactboolean (optional) Added in: v1.28#无论 setName 是否完全匹配:区分大小写并匹配整个字符串。默认为 false。当 setName 是正则表达式时将被忽略。请注意,完全匹配仍会去除空白字符。
-
setExpandedboolean (optional)#通常由
aria-expanded设置的属性。了解更多关于
aria-expanded的信息。 -
setIncludeHiddenboolean (optional)#控制是否匹配隐藏元素的选项。默认情况下,角色选择器仅匹配非隐藏元素,由 ARIA 定义。
了解更多关于
aria-hidden的信息。 -
一个通常存在于角色
heading、listitem、row、treeitem的数字属性,对<h1>-<h6>元素有默认值。了解更多关于
aria-level的信息。 -
setNameString | Pattern (optional)#可选择匹配可访问名称。默认情况下,匹配不区分大小写并搜索子字符串,使用setExact可控制此行为。
了解有关可访问名称的更多信息。
-
setPressedboolean (optional)#通常由
aria-pressed设置的属性。了解更多关于
aria-pressed的信息。 -
setSelectedboolean (optional)#通常由
aria-selected设置的属性。了解更多关于
aria-selected的信息。
-
返回
详情
角色选择器不能替代无障碍审查和符合性测试,而是提供关于ARIA指南的早期反馈。
🌐 Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
许多HTML元素都隐含着[定义角色](https://w3c.github.io/html-aam/#html-element-role-mappings),角色选择器会识别该角色。你可以在这里找到所有[支持的角色](https://www.w3.org/TR/wai-aria-1.2/#role_definitions)。ARIA 指南不建议通过将“role”和/或“aria-*”属性设置为默认值来重复隐式角色和属性。
🌐 Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.
getByTestId
Added in: v1.27通过测试 ID 定位元素。
🌐 Locate element by the test id.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<button data-testid="directions">Itinéraire</button>
你可以通过元素的测试 ID 来定位该元素:
🌐 You can locate the element by it's test id:
page.getByTestId("directions").click();
参数
返回
详情
默认情况下,data-testid 属性用作测试 ID。如果有必要,可以使用 Selectors.setTestIdAttribute() 来配置不同的测试 ID 属性。
🌐 By default, the data-testid attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.
getByText
Added in: v1.27允许定位包含给定文本的元素。
🌐 Allows locating elements that contain given text.
另请参阅 Locator.filter(),它允许按其他条件匹配,例如可访问角色,然后按文本内容进行筛选。
🌐 See also Locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.
用法
考虑以下 DOM 结构:
🌐 Consider the following DOM structure:
<div>Hello <span>world</span></div>
<div>Hello</div>
你可以通过文本子字符串、精确字符串或正则表达式进行定位:
🌐 You can locate by text substring, exact string, or a regular expression:
// Matches <span>
page.getByText("world");
// Matches first <div>
page.getByText("Hello world");
// Matches second <div>
page.getByText("Hello", new Page.GetByTextOptions().setExact(true));
// Matches both <div>s
page.getByText(Pattern.compile("Hello"));
// Matches second <div>
page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE));
参数
-
用于定位元素的文本。
-
optionsPage.GetByTextOptions(optional)
返回
详情
文本匹配总是会规范化空白字符,即使是完全匹配。例如,它会将多个空格变为一个,将换行符变为空格,并忽略开头和结尾的空白。
🌐 Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
类型为 button 和 submit 的输入元素是通过它们的 value 而不是文本内容来匹配的。例如,通过文本 "Log in" 定位会匹配 <input type=button value="Log in">。
🌐 Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.
getByTitle
Added in: v1.27允许通过标题属性定位元素。
🌐 Allows locating elements by their title attribute.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<span title='问题数量'>25 issues</span>
你可以通过标题文本找到问题后查看问题数:
🌐 You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");
参数
-
用于定位元素的文本。
-
optionsPage.GetByTitleOptions(optional)
返回
goBack
Added before v1.9返回主资源响应。如果有多个重定向,导航将以最后一次重定向的响应结束。如果无法回退,则返回 null。
🌐 Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go back, returns null.
导航到历史记录中的上一页。
🌐 Navigate to the previous page in history.
用法
Page.goBack();
Page.goBack(options);
参数
optionsPage.GoBackOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
goForward
Added before v1.9返回主资源响应。如果有多个重定向,导航将以最后一次重定向的响应结束。如果无法前进,则返回 null。
🌐 Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If cannot go forward, returns null.
导航到历史记录的下一页。
🌐 Navigate to the next page in history.
用法
Page.goForward();
Page.goForward(options);
参数
optionsPage.GoForwardOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
isClosed
Added before v1.9表示该页面已关闭。
🌐 Indicates that the page has been closed.
用法
Page.isClosed();
返回
locator
Added in: v1.14该方法返回一个元素定位器,可用于对该页面/框架执行操作。定位器在执行操作之前会立即解析为元素,因此对同一定位器进行的一系列操作实际上可能会在不同的DOM元素上执行。如果在这些操作之间DOM结构发生变化,就会出现这种情况。
🌐 The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.
用法
Page.locator(selector);
Page.locator(selector, options);
参数
-
解析 DOM 元素时使用的选择器。
-
optionsPage.LocatorOptions(optional)-
将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,
article拥有text=Playwright匹配<article><div>Playwright</div></article>。内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含
div的content,位于<article><content><div>Playwright</div></content></article>中。然而,查找包含article div的content会失败,因为内部定位器必须是相对的,不应使用content之外的任何元素。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
setHasNotLocator (optional) Added in: v1.33#匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含
div的article会匹配<article><span>Playwright</span></article>。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
setHasNotTextString | Pattern (optional) Added in: v1.33#匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入string时,匹配不区分大小写,并搜索子字符串。
-
setHasTextString | Pattern (optional)#匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,
"Playwright"可以匹配<article><div>Playwright</div></article>。
-
返回
mainFrame
Added before v1.9页面的主框架。页面保证有一个在导航期间持续存在的主框架。
🌐 The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
用法
Page.mainFrame();
返回
navigate
Added before v1.9返回主要资源响应。如果有多个重定向,导航将以第一个非重定向响应完成。
🌐 Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
如果出现以下情况,该方法将抛出错误:
🌐 The method will throw an error if:
- 存在 SSL 错误(例如,在自签名证书的情况下)。
- 目标网址无效。
- 在导航过程中超过了 setTimeout 的时间限制。
- 远程服务器没有响应或无法访问。
- 主要资源加载失败。
当远程服务器返回任何有效的 HTTP 状态码时,该方法不会抛出错误,包括 404 “未找到”和 500 “内部服务器错误”。 可以通过调用 Response.status() 来获取此类响应的状态码。
🌐 The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Response.status().
该方法要么抛出错误,要么返回主资源响应。唯一的例外是导航到 about:blank 或导航到相同 URL 但带有不同哈希,这种情况会成功并返回 null。
🌐 The method either throws an error or returns a main resource response. The only exceptions are navigation to about:blank or navigation to the same URL with a different hash, which would succeed and return null.
无头模式不支持导航到 PDF 文档。请参阅上游问题。
用法
Page.navigate(url);
Page.navigate(url, options);
参数
-
要导航到的页面的 URL。URL 应该包含协议,例如
https://。当通过上下文选项提供了 setBaseURL 并且传递的 URL 是一个路径时,它会通过new URL()构造函数进行合并。 -
optionsPage.NavigateOptions(optional)-
Referer 头的值。如果提供,它将优先于 Page.setExtraHTTPHeaders() 设置的 referer 头的值。
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
onceDialog
Added in: v1.10添加一次性 Dialog 处理程序。该处理程序将在下一个 Dialog 创建后立即被移除。
🌐 Adds one-off Dialog handler. The handler will be removed immediately after next Dialog is created.
page.onceDialog(dialog -> {
dialog.accept("foo");
});
// prints 'foo'
System.out.println(page.evaluate("prompt('Enter string:')"));
// prints 'null' as the dialog will be auto-dismissed because there are no handlers.
System.out.println(page.evaluate("prompt('Enter string:')"));
上面的代码相当于:
🌐 This code above is equivalent to:
Consumer<Dialog> handler = new Consumer<Dialog>() {
@Override
public void accept(Dialog dialog) {
dialog.accept("foo");
page.offDialog(this);
}
};
page.onDialog(handler);
// prints 'foo'
System.out.println(page.evaluate("prompt('Enter string:')"));
// prints 'null' as the dialog will be auto-dismissed because there are no handlers.
System.out.println(page.evaluate("prompt('Enter string:')"));
用法
Page.onceDialog(handler);
参数
-
接收 Dialog 对象,它必须调用 Dialog.accept() 或 Dialog.dismiss() 来处理对话框,否则页面将会冻结等待对话框,点击等操作将永远无法完成。
opener
Added before v1.9返回弹出页面的打开者,对于其他页面返回 null。如果打开者已经关闭,则返回 null。
🌐 Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.
用法
Page.opener();
返回
pageErrors
Added in: v1.56返回此页面的最多(当前为)200个最近页面错误。更多详情请参见 Page.onPageError(handler)。
🌐 Returns up to (currently) 200 last page errors from this page. See Page.onPageError(handler) for more details.
用法
Page.pageErrors();
返回
pause
Added in: v1.9暂停脚本执行。Playwright 将停止执行脚本,并等待用户在页面覆盖层中点击“继续”按钮或在 DevTools 控制台中调用 playwright.resume()。
🌐 Pauses script execution. Playwright will stop executing the script and wait for the user to either press the 'Resume' button in the page overlay or to call playwright.resume() in the DevTools console.
用户可以在暂停时检查选择器或执行手动操作。恢复将从暂停的位置继续运行原始脚本。
🌐 User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
此方法要求 Playwright 以有界面模式启动,并设置 setHeadless 选项为假值。
🌐 This method requires Playwright to be started in a headed mode, with a falsy setHeadless option.
用法
Page.pause();
返回
pdf
Added before v1.9返回 PDF 缓冲区。
🌐 Returns the PDF buffer.
page.pdf() 使用 print CSS 媒体生成页面的 PDF。要使用 screen 媒体生成 PDF,请在调用 page.pdf() 之前调用 Page.emulateMedia() :
默认情况下,page.pdf() 会生成带有修改颜色以适应打印的 PDF。使用 -webkit-print-color-adjust 属性可强制渲染精确颜色。
🌐 By default, page.pdf() generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust property to force rendering of exact colors.
用法
// Generates a PDF with "screen" media type.
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));
page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
setWidth、setHeight 和 setMargin 选项接受带有单位的值。未标注单位的值将被视为像素。
🌐 The setWidth, setHeight, and setMargin options accept values labeled with units. Unlabeled values are treated as pixels.
举几个例子:
🌐 A few examples:
page.pdf({width: 100})- 打印宽度设置为100像素page.pdf({width: '100px'})- 打印宽度设置为100像素page.pdf({width: '10cm'})- 打印宽度设置为10厘米。
所有可能的单位是:
🌐 All possible units are:
px- pixelin- inchcm- centimetermm- millimeter
setFormat 选项如下:
🌐 The setFormat options are:
Letter:8.5 英寸 x 11 英寸Legal:8.5 英寸 x 14 英寸Tabloid:11 英寸 x 17 英寸Ledger:17 英寸 x 11 英寸A0:33.1 英寸 x 46.8 英寸A1:23.4 英寸 x 33.1 英寸A2:16.54 英寸 x 23.4 英寸A3:11.7 英寸 x 16.54 英寸A4:8.27 英寸 x 11.7 英寸A5:5.83 英寸 x 8.27 英寸A6:4.13 英寸 x 5.83 英寸
setHeaderTemplate 和 setFooterTemplate 标记有以下限制: > 1. 模板内的脚本标签不会被执行。 > 2. 模板中无法显示页面样式。 :::
参数
optionsPage.PdfOptions(optional)-
setDisplayHeaderFooterboolean (optional)#显示页眉和页脚。默认为
false。 -
setFooterTemplateString (optional)#用于打印页脚的 HTML 模板。应使用与 setHeaderTemplate 相同的格式。
-
setHeaderTemplateString (optional)#打印页眉的 HTML 模板。应为有效的 HTML 标记,并使用以下类将打印值注入其中:
'date'格式化打印日期'title'文档标题'url'文档位置'pageNumber'当前页码- 文档中共有
'totalPages'页
-
纸张高度,接受标有单位的值。
-
setLandscapeboolean (optional)#纸张方向。默认为
false。 -
setMarginMargin (optional)#-
setTopString (optional)上边距,接受带单位的数值。默认值为
0。 -
setRightString (optional)右边距,接受带单位的数值。默认值为
0。 -
setBottomString (optional)底部边距,接受带单位的数值。默认值为
0。 -
setLeftString (optional)左边距,接受带单位标注的数值。默认值为
0。
纸张边距,默认为无。
-
-
setOutlineboolean (optional) Added in: v1.42#是否将文档大纲嵌入到 PDF 中。默认值为
false。 -
setPageRangesString (optional)#要打印的页码范围,例如,'1-5, 8, 11-13'。默认值为空字符串,表示打印所有页面。
-
保存 PDF 的文件路径。如果 setPath 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,PDF 将不会保存到磁盘上。
-
setPreferCSSPageSizeboolean (optional)#使页面中声明的任何 CSS
@page尺寸优先于在 setWidth、setHeight 或 setFormat 选项中声明的尺寸。默认值为false,内容将按纸张尺寸进行缩放。 -
setPrintBackgroundboolean (optional)#打印背景图形。默认为
false。 -
网页渲染的缩放比例。默认为
1。缩放比例必须在 0.1 到 2 之间。 -
setTaggedboolean (optional) Added in: v1.42#是否生成带标签(可访问)的 PDF。默认值为
false。 -
纸张宽度,接受标有单位的值。
-
返回
reload
Added before v1.9此方法会重新加载当前页面,就像用户触发了浏览器刷新一样。返回主资源响应。如果发生多次重定向,导航将以最后一次重定向的响应结果结束。
🌐 This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
用法
Page.reload();
Page.reload(options);
参数
optionsPage.ReloadOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
removeLocatorHandler
Added in: v1.44移除由 Page.addLocatorHandler() 为特定定位器添加的所有定位器处理程序。
🌐 Removes all locator handlers added by Page.addLocatorHandler() for a specific locator.
用法
Page.removeLocatorHandler(locator);
参数
-
传递给 Page.addLocatorHandler() 的定位器。
返回
requestGC
Added in: v1.48请求页面执行垃圾回收。请注意,无法保证所有不可达对象都会被回收。
🌐 Request the page to perform garbage collection. Note that there is no guarantee that all unreachable objects will be collected.
这对于帮助检测内存泄漏非常有用。例如,如果你的页面有一个可能会泄漏的大对象 'suspect',你可以使用 WeakRef 来检查它是否没有泄漏。
🌐 This is useful to help detect memory leaks. For example, if your page has a large object 'suspect' that might be leaked, you can check that it does not leak by using a WeakRef.
// 1. In your page, save a WeakRef for the "suspect".
page.evaluate("globalThis.suspectWeakRef = new WeakRef(suspect)");
// 2. Request garbage collection.
page.requestGC();
// 3. Check that weak ref does not deref to the original object.
assertTrue(page.evaluate("!globalThis.suspectWeakRef.deref()"));
用法
Page.requestGC();
返回
requests
Added in: v1.56返回此页面最多(当前)最近的 100 个网络请求。更多详情请参见 Page.onRequest(handler)。
🌐 Returns up to (currently) 100 last network request from this page. See Page.onRequest(handler) for more details.
返回的请求应立即被访问,否则它们可能会被收集,以防止随着新请求的到来导致内存无限增长。一旦被收集,就几乎无法检索有关该请求的大部分信息。
🌐 Returned requests should be accessed immediately, otherwise they might be collected to prevent unbounded memory growth as new requests come in. Once collected, retrieving most information about the request is impossible.
请注意,通过 Page.onRequest(handler) 请求报告的请求不会被收集,因此在使用 Page.requests() 实现高效内存使用与通过 Page.onRequest(handler) 获取的可用信息量之间存在权衡。
🌐 Note that requests reported through the Page.onRequest(handler) request are not collected, so there is a trade off between efficient memory usage with Page.requests() and the amount of available information reported through Page.onRequest(handler).
用法
Page.requests();
返回
route
Added before v1.9路由提供了修改页面触发的网络请求的功能。
🌐 Routing provides the capability to modify network requests that are made by a page.
一旦启用路由,每个与 url 模式匹配的请求都将停止,除非它继续、完成或中止。
🌐 Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
只有在响应为重定向时,处理程序才会被调用于第一个 URL。
🌐 The handler will only be called for the first url if the response is a redirect.
Page.route() 不会拦截被 Service Worker 拦截的请求。请参见 此 问题。我们建议在使用请求拦截时禁用 Service Worker,可通过将 setServiceWorkers 设置为 'block' 来实现。
Page.route() 不会拦截弹出页面的第一个请求。请改用 BrowserContext.route() 。
用法
中止所有图片请求的简单处理程序的示例:
🌐 An example of a naive handler that aborts all image requests:
Page page = browser.newPage();
page.route("**/*.{png,jpg,jpeg}", route -> route.abort());
page.navigate("https://example.com");
browser.close();
或使用正则表达式模式的相同片段:
🌐 or the same snippet using a regex pattern instead:
Page page = browser.newPage();
page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
page.navigate("https://example.com");
browser.close();
可以检查请求以决定路由操作。例如,模拟所有包含某些 POST 数据的请求,而将所有其他请求保持原样:
🌐 It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> {
if (route.request().postData().contains("my-string"))
route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
else
route.resume();
});
当请求同时匹配两个处理程序时,页面路由优先于浏览器上下文路由(通过 BrowserContext.route() 设置)。
🌐 Page routes take precedence over browser context routes (set up with BrowserContext.route()) when request matches both handlers.
要删除带有其处理程序的路由,可以使用 Page.unroute()。
🌐 To remove a route with its handler you can use Page.unroute().
启用路由会禁用 HTTP 缓存。
🌐 Enabling routing disables http cache.
参数
-
urlString | Pattern | Predicate<String>#在路由过程中用于匹配的通配符模式、正则表达式模式或接收 [URL] 的谓词。如果在上下文选项中设置了 setBaseURL,并且提供的 URL 是不以
*开头的字符串,则使用new URL()构造函数进行解析。 -
处理程序函数来路由请求。
-
optionsPage.RouteOptions(optional)
返回
routeFromHAR
Added in: v1.23如果指定,页面中发出的网络请求将从 HAR 文件中提供。阅读更多关于从 HAR 重放的信息。
🌐 If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.
Playwright 不会处理来自 HAR 文件的、被服务工作进程拦截的请求。请参见此问题。我们建议在使用请求拦截时禁用服务工作进程,通过将setServiceWorkers设置为'block'来实现。
🌐 Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting setServiceWorkers to 'block'.
用法
Page.routeFromHAR(har);
Page.routeFromHAR(har, options);
参数
-
指向包含预录网络数据的 HAR 文件的路径。如果
path是相对路径,则相对于当前工作目录进行解析。 -
optionsPage.RouteFromHAROptions(optional)-
setNotFoundenum HarNotFound { ABORT, FALLBACK }(optional)#- 如果设置为“中止”,任何在 HAR 文件中未找到的请求都将被中止。
- 如果设置为“fallback”,缺失的请求将发送到网络。
默认为中止。
-
如果指定,将使用实际的网络信息更新给定的 HAR,而不是从文件提供。当调用 BrowserContext.close() 时,文件将写入磁盘。
-
setUpdateContentenum RouteFromHarUpdateContentPolicy { EMBED, ATTACH }(optional) Added in: v1.32#可选设置,用于控制资源内容管理。如果指定
attach,资源将作为单独的文件或 ZIP 压缩包中的条目进行保存。如果指定embed,内容将存储在 HAR 文件中。 -
setUpdateModeenum HarMode { FULL, MINIMAL }(optional) Added in: v1.32#当设置为
minimal时,仅记录从 HAR 路由所需的信息。这会省略在从 HAR 回放时不使用的大小、时间、页面、Cookies、安全性以及其他类型的 HAR 信息。默认值为minimal。 -
setUrlString | Pattern (optional)#用于匹配请求 URL 的通配符模式、正则表达式或谓词。只有 URL 匹配该模式的请求才会从 HAR 文件中提供服务。如果未指定,则所有请求都将从 HAR 文件中提供服务。
-
返回
routeWebSocket
Added in: v1.48此方法允许修改页面建立的 websocket 连接。
🌐 This method allows to modify websocket connections that are made by the page.
请注意,只有在调用此方法后创建的 WebSocket 才会被路由。建议在导航页面之前调用此方法。
🌐 Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before navigating the page.
用法
下面是一个简单的模拟示例,它可以回应单条消息。更多细节和示例请参见 WebSocketRoute。
🌐 Below is an example of a simple mock that responds to a single message. See WebSocketRoute for more details and examples.
page.routeWebSocket("/ws", ws -> {
ws.onMessage(frame -> {
if ("request".equals(frame.text()))
ws.send("response");
});
});
参数
-
urlString | Pattern | Predicate<String>#只有与此模式匹配的 URL 的 WebSocket 才会被路由。字符串模式可以相对于 setBaseURL 上下文选项。
-
handlerConsumer<WebSocketRoute>#路由 WebSocket 的处理程序函数。
返回
screenshot
Added before v1.9返回带有捕获的屏幕截图的缓冲区。
🌐 Returns the buffer with the captured screenshot.
用法
Page.screenshot();
Page.screenshot(options);
参数
optionsPage.ScreenshotOptions(optional)-
setAnimationsenum ScreenshotAnimations { DISABLED, ALLOW }(optional)#当设置为
"disabled"时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:- 有限动画会被快进至完成,因此它们会触发
transitionend事件。 - 无限动画被取消到初始状态,然后在屏幕截图后播放。
默认值为
"allow",不会改变动画。 - 有限动画会被快进至完成,因此它们会触发
-
setCaretenum ScreenshotCaret { HIDE, INITIAL }(optional)#当设置为
"hide"时,截图将隐藏文本光标。当设置为"initial"时,文本光标的行为不会改变。默认值为"hide"。 -
setClipClip (optional)#-
setXdouble剪辑区域左上角的 x 坐标
-
setYdouble剪辑区域左上角的 y 坐标
-
setWidthdouble剪裁区域的宽度
-
setHeightdouble剪裁区域的高度
指定对结果图片进行裁剪的对象。
-
-
setFullPageboolean (optional)#当为真时,会截取整个可滚动页面的截图,而不是当前可见的视口。默认值为
false。 -
setMaskList<Locator> (optional)#指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉红色框
#FF00FF覆盖(可通过 setMaskColor 自定义),完全覆盖其边界框。该遮罩也会应用于不可见元素,参见 仅匹配可见元素 以禁用此功能。 -
setMaskColorString (optional) Added in: v1.35#指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色
#FF00FF。 -
setOmitBackgroundboolean (optional)#隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于
jpeg图片。默认值为false。 -
保存图片的文件路径。截图类型将根据文件扩展名推断。如果 setPath 是相对路径,则相对于当前工作目录解析。如果未提供路径,图片将不会保存到磁盘。
-
图片质量,范围为0-100。不适用于
png图片。 -
setScaleenum ScreenshotScale { CSS, DEVICE }(optional)#当设置为
"css"时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用"device"选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。默认为
"device"。 -
setStyleString (optional) Added in: v1.41#在截图时要应用的样式表文本。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。此样式表可以穿透 Shadow DOM 并应用于内部框架。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTypeenum ScreenshotType { PNG, JPEG }(optional)#指定截图类型,默认为
png。
-
返回
setContent
Added before v1.9该方法在内部调用了 document.write(),继承了其所有特定的特性和行为。
🌐 This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
用法
Page.setContent(html);
Page.setContent(html, options);
参数
-
要分配给页面的 HTML 标记。
-
optionsPage.SetContentOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
setDefaultNavigationTimeout
Added before v1.9此设置将更改以下方法和相关快捷方式的默认最大导航时间:
🌐 This setting will change the default maximum navigation time for the following methods and related shortcuts:
- Page.goBack()
- Page.goForward()
- Page.navigate()
- Page.reload()
- Page.setContent()
- Page.waitForNavigation()
- Page.waitForURL()
用法
Page.setDefaultNavigationTimeout(timeout);
参数
setDefaultTimeout
Added before v1.9此设置将更改所有接受 timeout 选项的方法的默认最大时间。
🌐 This setting will change the default maximum time for all the methods accepting timeout option.
用法
Page.setDefaultTimeout(timeout);
参数
setExtraHTTPHeaders
Added before v1.9额外的 HTTP 标头将随页面发起的每个请求一起发送。
🌐 The extra HTTP headers will be sent with every request the page initiates.
Page.setExtraHTTPHeaders() 不保证发送请求中头部的顺序。
用法
Page.setExtraHTTPHeaders(headers);
参数
返回
setViewportSize
Added before v1.9在单个浏览器中,如果有多个页面,每个页面可以有自己的视口大小。然而,Browser.newContext() 允许一次性为上下文中的所有页面设置视口大小(以及更多设置)。
🌐 In the case of multiple pages in a single browser, each page can have its own viewport size. However, Browser.newContext() allows to set viewport size (and more) for all pages in the context at once.
Page.setViewportSize() 会调整页面大小。许多网站没有考虑手机尺寸变化,所以你应该在导航到页面之前设置视口大小。Page.setViewportSize() 也会重置 screen 大小,如果你需要更好地控制这些属性,请使用带有 screen 和 viewport 参数的 Browser.newContext()。
用法
Page page = browser.newPage();
page.setViewportSize(640, 480);
page.navigate("https://example.com");
参数
返回
title
Added before v1.9返回页面的标题。
🌐 Returns the page's title.
用法
Page.title();
返回
unroute
Added before v1.9移除使用 Page.route() 创建的路由。当未指定 handler 时,将移除该 url 的所有路由。
🌐 Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
用法
Page.unroute(url);
Page.unroute(url, handler);
参数
-
urlString | Pattern | Predicate<String>#在路由期间接收 [URL] 进行匹配的 glob 模式、正则表达式模式或谓词。
-
handlerConsumer<Route> (optional)#用于路由请求的可选处理程序函数。
返回
unrouteAll
Added in: v1.41删除所有使用 Page.route() 和 Page.routeFromHAR() 创建的路由。
🌐 Removes all routes created with Page.route() and Page.routeFromHAR().
用法
Page.unrouteAll();
返回
url
Added before v1.9用法
Page.url();
返回
video
Added before v1.9与此页面关联的视频对象。
🌐 Video object associated with this page.
用法
Page.video();
返回
viewportSize
Added before v1.9用法
Page.viewportSize();
返回
waitForClose
Added in: v1.11执行操作并等待页面关闭。
🌐 Performs action and waits for the Page to close.
用法
Page.waitForClose(callback);
Page.waitForClose(callback, options);
参数
-
optionsPage.WaitForCloseOptions(optional)-
setTimeoutdouble (optional) Added in: v1.9#等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 BrowserContext.setDefaultTimeout() 来更改默认值。
-
-
callbackRunnable Added in: v1.9#执行触发事件的操作的回调。
返回
waitForCondition
Added in: v1.32该方法会阻塞,直到条件返回为真。在方法等待条件时,所有 Playwright 事件都会被分发。
🌐 The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.
用法
使用此方法等待依赖于页面事件的条件:
🌐 Use the method to wait for a condition that depends on page events:
List<String> messages = new ArrayList<>();
page.onConsoleMessage(m -> messages.add(m.text()));
page.getByText("Submit button").click();
page.waitForCondition(() -> messages.size() > 3);
参数
-
condition[BooleanSupplier]#等待的条件。
-
optionsPage.WaitForConditionOptions(optional)-
等待的最长时间,以毫秒为单位。默认值为
30000(30 秒)。传入0可禁用超时。可以使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法更改默认值。
-
返回
waitForConsoleMessage
Added in: v1.9执行操作并等待页面记录 ConsoleMessage。如果提供了谓词,会将 ConsoleMessage 的值传入 predicate 函数,并等待 predicate(message) 返回真值。如果在 Page.onConsoleMessage(handler) 事件触发之前页面被关闭,将会抛出错误。
🌐 Performs action and waits for a ConsoleMessage to be logged by in the page. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the Page.onConsoleMessage(handler) event is fired.
用法
Page.waitForConsoleMessage(callback);
Page.waitForConsoleMessage(callback, options);
参数
-
optionsPage.WaitForConsoleMessageOptions(optional)-
setPredicatePredicate<ConsoleMessage> (optional)#接收 ConsoleMessage 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 BrowserContext.setDefaultTimeout() 来更改默认值。
-
-
执行触发事件的操作的回调。
返回
waitForDownload
Added in: v1.9执行操作并等待新的[下载]。如果提供了谓词,它会将[下载]值传入predicate函数,并等待predicate(download)返回真值。如果在触发下载事件之前页面被关闭,将抛出错误。
🌐 Performs action and waits for a new Download. If predicate is provided, it passes Download value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.
用法
Page.waitForDownload(callback);
Page.waitForDownload(callback, options);
参数
-
optionsPage.WaitForDownloadOptions(optional) -
执行触发事件的操作的回调。
返回
waitForFileChooser
Added in: v1.9执行操作并等待创建新的 FileChooser。如果提供了谓词,它会将 FileChooser 值传入 predicate 函数,并等待 predicate(fileChooser) 返回一个真值。如果在文件选择器打开之前页面被关闭,将抛出错误。
🌐 Performs action and waits for a new FileChooser to be created. If predicate is provided, it passes FileChooser value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.
用法
Page.waitForFileChooser(callback);
Page.waitForFileChooser(callback, options);
参数
-
optionsPage.WaitForFileChooserOptions(optional)-
setPredicatePredicate<FileChooser> (optional)#接收 FileChooser 对象,并在等待应被解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 BrowserContext.setDefaultTimeout() 来更改默认值。
-
-
执行触发事件的操作的回调。
返回
waitForFunction
Added before v1.9当 expression 返回真值时返回。它解析为该真值的 JSHandle。
🌐 Returns when the expression returns a truthy value. It resolves to a JSHandle of the truthy value.
用法
Page.waitForFunction() 可用于观察视口大小的变化:
🌐 The Page.waitForFunction() can be used to observe viewport size change:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch();
Page page = browser.newPage();
page.setViewportSize(50, 50);
page.waitForFunction("() => window.innerWidth < 100");
browser.close();
}
}
}
要向 Page.waitForFunction() 函数的谓词传递参数:
🌐 To pass an argument to the predicate of Page.waitForFunction() function:
String selector = ".foo";
page.waitForFunction("selector => !!document.querySelector(selector)", selector);
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
-
optionsPage.WaitForFunctionOptions(optional)-
setPollingIntervaldouble (optional)#如果指定,则将其视为函数执行的毫秒间隔。默认情况下,如果未指定该选项,expression 会在
requestAnimationFrame回调中执行。 -
等待的最长时间,以毫秒为单位。默认值为
30000(30 秒)。传入0可禁用超时。可以使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法更改默认值。
-
返回
waitForLoadState
Added before v1.9当达到所需的负载状态时返回。
🌐 Returns when the required load state has been reached.
当页面达到所需的加载状态时,这将被解决,默认状态为 load。调用此方法时,导航必须已经提交。如果当前文档已经达到所需状态,则会立即解决。
🌐 This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
大多数情况下,这种方法是不需要的,因为 Playwright 会在每个操作之前自动等待。
🌐 Most of the time, this method is not needed because Playwright auto-waits before every action.
用法
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
page.waitForLoadState(); // The promise resolves after "load" event.
Page popup = page.waitForPopup(() -> {
page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup.
});
// Wait for the "DOMContentLoaded" event
popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
System.out.println(popup.title()); // Popup is ready to use.
参数
-
stateenum LoadState { LOAD, DOMCONTENTLOADED, NETWORKIDLE }(optional)#可选的加载状态,默认值为
load。如果在加载当前文档时该状态已达到,方法会立即完成。可以是以下之一:'load'- 等待load事件触发。'domcontentloaded'- 等待DOMContentLoaded事件触发。'networkidle'- 不建议 等待直到至少500毫秒内没有网络连接。不要使用此方法进行测试,而应依赖网络断言来评估准备情况。
-
optionsPage.WaitForLoadStateOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
waitForPopup
Added in: v1.9执行操作并等待弹出窗口 Page。如果提供了谓词,它会将 [Popup] 值传入 predicate 函数,并等待 predicate(page) 返回真值。如果在弹出事件触发前页面被关闭,将会抛出错误。
🌐 Performs action and waits for a popup Page. If predicate is provided, it passes [Popup] value into the predicate function and waits for predicate(page) to return a truthy value. Will throw an error if the page is closed before the popup event is fired.
用法
Page.waitForPopup(callback);
Page.waitForPopup(callback, options);
参数
-
optionsPage.WaitForPopupOptions(optional) -
执行触发事件的操作的回调。
返回
waitForRequest
Added before v1.9等待匹配的请求并返回它。有关事件的更多详细信息,请参见等待事件。
🌐 Waits for the matching request and returns it. See waiting for event for more details about events.
用法
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.getByText("trigger request").click();
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.getByText("trigger request").click();
});
参数
-
urlOrPredicateString | Pattern | Predicate<Request>#请求 URL 字符串、正则表达式或接收 Request 对象的谓词。当通过上下文选项提供了 setBaseURL 且传入的 URL 是路径时,它会通过
new URL()构造函数进行合并。 -
optionsPage.WaitForRequestOptions(optional)-
最大等待时间(以毫秒为单位),默认值为 30 秒,传入
0可禁用超时。默认值可以通过使用 Page.setDefaultTimeout() 方法进行更改。
-
-
callbackRunnable Added in: v1.9#执行触发事件的操作的回调。
返回
waitForRequestFinished
Added in: v1.12执行操作并等待 Request 加载完成。如果提供了谓词,它会将 Request 的值传递给 predicate 函数,并等待 predicate(request) 返回一个真值。如果在触发 Page.onRequestFinished(handler) 事件之前页面被关闭,将抛出错误。
🌐 Performs action and waits for a Request to finish loading. If predicate is provided, it passes Request value into the predicate function and waits for predicate(request) to return a truthy value. Will throw an error if the page is closed before the Page.onRequestFinished(handler) event is fired.
用法
Page.waitForRequestFinished(callback);
Page.waitForRequestFinished(callback, options);
参数
-
optionsPage.WaitForRequestFinishedOptions(optional) -
执行触发事件的操作的回调。
返回
waitForResponse
Added before v1.9返回匹配的响应。有关事件的更多详细信息,请参阅等待事件。
🌐 Returns the matched response. See waiting for event for more details about events.
用法
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.getByText("trigger response").click();
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> {
// Triggers the response
page.getByText("trigger response").click();
});
参数
-
urlOrPredicateString | Pattern | Predicate<Response>#请求 URL 字符串、正则表达式或接收 Response 对象的谓词。当通过上下文选项提供了 setBaseURL 且传入的 URL 是路径时,它会通过
new URL()构造函数进行合并。 -
optionsPage.WaitForResponseOptions(optional)-
最长等待时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法更改。
-
-
callbackRunnable Added in: v1.9#执行触发事件的操作的回调。
返回
waitForURL
Added in: v1.11等待主框架导航到给定的 URL。
🌐 Waits for the main frame to navigate to the given URL.
用法
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**/target.html");
参数
-
urlString | Pattern | Predicate<String>#一个通配符模式、正则表达式模式或接收 [URL] 的谓词,用于在等待导航时进行匹配。请注意,如果参数是没有通配符字符的字符串,该方法将等待导航到与该字符串完全相同的 URL。
-
optionsPage.WaitForURLOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
返回
waitForWebSocket
Added in: v1.9执行操作并等待新的 WebSocket。如果提供了谓词,它会将 WebSocket 值传入 predicate 函数,并等待 predicate(webSocket) 返回一个真值。如果在 WebSocket 事件触发前页面被关闭,将抛出错误。
🌐 Performs action and waits for a new WebSocket. If predicate is provided, it passes WebSocket value into the predicate function and waits for predicate(webSocket) to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.
用法
Page.waitForWebSocket(callback);
Page.waitForWebSocket(callback, options);
参数
-
optionsPage.WaitForWebSocketOptions(optional) -
执行触发事件的操作的回调。
返回
waitForWorker
Added in: v1.9执行操作并等待新的 Worker。如果提供了谓词,它会将 Worker 值传入 predicate 函数,并等待 predicate(worker) 返回一个真值。如果在触发 worker 事件之前页面被关闭,将会抛出错误。
🌐 Performs action and waits for a new Worker. If predicate is provided, it passes Worker value into the predicate function and waits for predicate(worker) to return a truthy value. Will throw an error if the page is closed before the worker event is fired.
用法
Page.waitForWorker(callback);
Page.waitForWorker(callback, options);
参数
-
optionsPage.WaitForWorkerOptions(optional) -
执行触发事件的操作的回调。
返回
workers
Added before v1.9此方法返回与页面关联的所有专用 WebWorkers。
🌐 This method returns all of the dedicated WebWorkers associated with the page.
这不包含 ServiceWorkers
🌐 This does not contain ServiceWorkers
用法
Page.workers();
返回
属性
🌐 Properties
clock()
Added in: v1.45Playwright 能够模拟时钟和时间的流逝。
🌐 Playwright has ability to mock clock and passage of time.
用法
Page.clock()
返回
keyboard()
Added before v1.9用法
Page.keyboard()
返回
mouse()
Added before v1.9用法
Page.mouse()
返回
request()
Added in: v1.16与此页面关联的 API 测试助手。此方法返回与页面上下文中的 BrowserContext.request() 相同的实例。更多详情请参见 BrowserContext.request()。
🌐 API testing helper associated with this page. This method returns the same instance as BrowserContext.request() on the page's context. See BrowserContext.request() for more details.
用法
Page.request()
返回
touchscreen()
Added before v1.9用法
Page.touchscreen()
返回
事件
🌐 Events
onClose(handler)
Added before v1.9页面关闭时触发。
🌐 Emitted when the page closes.
用法
Page.onClose(handler)
事件数据
onConsoleMessage(handler)
Added before v1.9当页面中的 JavaScript 调用某个控制台 API 方法时触发,例如 console.log 或 console.dir。
🌐 Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.
console.log 传入的参数可以在 ConsoleMessage 事件处理程序的参数中使用。
🌐 The arguments passed into console.log are available on the ConsoleMessage event handler argument.
用法
page.onConsoleMessage(msg -> {
for (int i = 0; i < msg.args().size(); ++i)
System.out.println(i + ": " + msg.args().get(i).jsonValue());
});
page.evaluate("() => console.log('hello', 5, { foo: 'bar' })");
事件数据
onCrash(handler)
Added before v1.9当页面崩溃时触发。如果浏览器页面尝试分配过多内存,可能会导致页面崩溃。当页面崩溃时,正在进行的操作和后续操作都会抛出异常。
🌐 Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.
处理崩溃最常见的方法是捕获异常:
🌐 The most common way to deal with crashes is to catch an exception:
try {
// Crash might happen during a click.
page.click("button");
// Or while waiting for an event.
page.waitForPopup(() -> {});
} catch (PlaywrightException e) {
// When the page crashes, exception message contains "crash".
}
用法
Page.onCrash(handler)
事件数据
onDialog(handler)
Added before v1.9当出现 JavaScript 对话框时触发,例如 alert、prompt、confirm 或 beforeunload。监听器必须要么 Dialog.accept(),要么 Dialog.dismiss() 对话框——否则页面会冻结等待对话框,像点击这样的操作将永远无法完成。
🌐 Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener must either Dialog.accept() or Dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.
用法
page.onDialog(dialog -> {
dialog.accept();
});
当没有 Page.onDialog(handler) 或 BrowserContext.onDialog(handler) 监听器时,所有对话框会被自动关闭。
事件数据
onDOMContentLoaded(handler)
Added in: v1.9当 JavaScript DOMContentLoaded 事件被分发时触发。
🌐 Emitted when the JavaScript DOMContentLoaded event is dispatched.
用法
Page.onDOMContentLoaded(handler)
事件数据
onDownload(handler)
Added before v1.9当附件下载开始时触发。用户可以通过传入的 Download 实例访问下载内容的基本文件操作。
🌐 Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.
用法
Page.onDownload(handler)
事件数据
onFileChooser(handler)
Added in: v1.9当应该出现文件选择器时会触发此事件,例如点击 <input type=file> 之后。Playwright 可以通过使用 FileChooser.setFiles() 设置输入文件来响应此事件,这些文件随后可以被上传。
🌐 Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using FileChooser.setFiles() that can be uploaded after that.
page.onFileChooser(fileChooser -> {
fileChooser.setFiles(Paths.get("/tmp/myfile.pdf"));
});
用法
Page.onFileChooser(handler)
事件数据
onFrameAttached(handler)
Added in: v1.9当附加框架时触发。
🌐 Emitted when a frame is attached.
用法
Page.onFrameAttached(handler)
事件数据
onFrameDetached(handler)
Added in: v1.9当框架分离时触发。
🌐 Emitted when a frame is detached.
用法
Page.onFrameDetached(handler)
事件数据
onFrameNavigated(handler)
Added in: v1.9当框架导航到新的 url 时触发。
🌐 Emitted when a frame is navigated to a new url.
用法
Page.onFrameNavigated(handler)
事件数据
onLoad(handler)
Added before v1.9当 JavaScript load 事件被分发时触发。
🌐 Emitted when the JavaScript load event is dispatched.
用法
Page.onLoad(handler)
事件数据
onPageError(handler)
Added in: v1.9当页面内发生未捕获的异常时触发。
🌐 Emitted when an uncaught exception happens within the page.
// Log all uncaught errors to the terminal
page.onPageError(exception -> {
System.out.println("Uncaught exception: " + exception);
});
// Navigate to a page with an exception.
page.navigate("data:text/html,<script>throw new Error('Test')</script>");
用法
Page.onPageError(handler)
事件数据
onPopup(handler)
Added before v1.9当页面打开新标签页或窗口时触发。此事件会与 BrowserContext.onPage(handler) 一起触发,但仅针对与此页面相关的弹出窗口。
🌐 Emitted when the page opens a new tab or window. This event is emitted in addition to the BrowserContext.onPage(handler), but only for popups relevant to this page.
页面最早可用的时刻是在它导航到初始 URL 时。例如,当使用 window.open('http://example.com') 打开弹出窗口时,当网络请求到 "http://example.com" 完成并且其响应开始在弹出窗口中加载时,将触发此事件。如果你想要路由/监听此网络请求,请使用 BrowserContext.route() 和 BrowserContext.onRequest(handler),而不是 Page 上的类似方法。
🌐 The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to this network request, use BrowserContext.route() and BrowserContext.onRequest(handler) respectively instead of similar methods on the Page.
Page popup = page.waitForPopup(() -> {
page.getByText("open the popup").click();
});
System.out.println(popup.evaluate("location.href"));
使用 Page.waitForLoadState() 等待页面达到特定状态(在大多数情况下你不需要使用它)。
用法
Page.onPopup(handler)
事件数据
onRequest(handler)
Added before v1.9当页面发出请求时触发。[request] 对象是只读的。要拦截和修改请求,请参见 [Page.route()](/api/class-page.mdx#page-route) 或 [BrowserContext.route()](/api/class-browsercontext.mdx#browser-context-route)。
🌐 Emitted when a page issues a request. The request object is read-only. In order to intercept and mutate requests, see Page.route() or BrowserContext.route().
用法
Page.onRequest(handler)
事件数据
onRequestFailed(handler)
Added in: v1.9当请求失败时触发,例如超时。
🌐 Emitted when a request fails, for example by timing out.
page.onRequestFailed(request -> {
System.out.println(request.url() + " " + request.failure());
});
HTTP 错误响应,例如 404 或 503,从 HTTP 的角度来看仍然是成功的响应,因此请求将通过 Page.onRequestFinished(handler) 事件完成,而不是通过 Page.onRequestFailed(handler)。只有当客户端无法从服务器获取 HTTP 响应时,例如由于网络错误 net::ERR_FAILED,请求才会被视为失败。
用法
Page.onRequestFailed(handler)
事件数据
onRequestFinished(handler)
Added in: v1.9当请求在下载响应主体后成功完成时触发。对于成功的响应,事件的顺序是 request、response 和 requestfinished。
🌐 Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished.
用法
Page.onRequestFinished(handler)
事件数据
onResponse(handler)
Added before v1.9当请求的 response 状态和头信息被接收时触发。对于成功的响应,事件的顺序是 request、response 和 requestfinished。
🌐 Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished.
用法
Page.onResponse(handler)
事件数据
onWebSocket(handler)
Added in: v1.9当发送 WebSocket 请求时触发。
🌐 Emitted when WebSocket request is sent.
用法
Page.onWebSocket(handler)
事件数据
onWorker(handler)
Added before v1.9当页面生成专用的 WebWorker 时触发。
🌐 Emitted when a dedicated WebWorker is spawned by the page.
用法
Page.onWorker(handler)
事件数据
已弃用
🌐 Deprecated
check
Added before v1.9请改为使用基于定位器的 Locator.check()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.check() instead. Read more about locators.
此方法通过执行以下步骤来检查匹配 selector 的元素:
🌐 This method checks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 确保匹配的元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 在元素中心点击。
- 确保该元素现在已被选中。如果没有,该方法会抛出异常。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时时间将禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
Page.check(selector);
Page.check(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.CheckOptions(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setPositionPosition (optional) Added in: v1.11#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
click
Added before v1.9请改为使用基于定位器的 Locator.click()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.click() instead. Read more about locators.
此方法通过执行以下步骤点击与 selector 匹配的元素:
🌐 This method clicks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 点击元素中心,或指定的 setPosition 位置。
- 等待已启动的导航成功或失败,除非设置了 setNoWaitAfter 选项。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
Page.click(selector);
Page.click(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.ClickOptions(optional)-
setButtonenum MouseButton { LEFT, RIGHT, MIDDLE }(optional)#默认为
left。 -
默认为 1。请参阅 UIEvent.detail。
-
mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
setModifiersList<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
setNoWaitAfterboolean (optional)#已弃用该选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
setPositionPosition (optional)#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
dblclick
Added before v1.9请改用基于定位器的 Locator.dblclick()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.dblclick() instead. Read more about locators.
此方法通过执行以下步骤对匹配 selector 的元素进行双击:
🌐 This method double clicks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 在元素中心或指定的 setPosition 处双击。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时时间将禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
page.dblclick() 触发两个 click 事件和一个 dblclick 事件。
用法
Page.dblclick(selector);
Page.dblclick(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.DblclickOptions(optional)-
setButtonenum MouseButton { LEFT, RIGHT, MIDDLE }(optional)#默认为
left。 -
mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
setModifiersList<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。
-
此选项无效。
-
setPositionPosition (optional)#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
返回
dispatchEvent
Added before v1.9请改用基于定位器的 Locator.dispatchEvent()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.dispatchEvent() instead. Read more about locators.
下面的代码片段会在该元素上触发 click 事件。无论元素的可见状态如何,都会触发 click。这相当于调用 element.click()。
🌐 The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().
用法
page.dispatchEvent("button#submit", "click");
在底层,它会根据给定的 type 创建一个事件实例,使用 eventInit 属性初始化该事件,并在元素上分发它。事件类型是 composed、cancelable,默认情况下会冒泡。
🌐 Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.
由于 eventInit 是特定于事件的,请查阅事件文档以获取初始属性列表:
🌐 Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:
- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
如果你希望实时对象被传递到事件中,你也可以将 JSHandle 指定为属性值:
🌐 You can also specify JSHandle as the property value if you want live objects to be passed into the event:
// Note you can only create DataTransfer in Chromium and Firefox
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
page.dispatchEvent("#source", "dragstart", arg);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
DOM 事件类型:
"click"、"dragstart"等 -
eventInitEvaluationArgument (optional)#可选的特定于事件的初始化属性。
-
optionsPage.DispatchEventOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
evalOnSelector
Added in: v1.9此方法不会等待元素通过可操作性检查,因此可能导致测试不稳定。建议使用 Locator.evaluate()、其他 Locator 辅助方法或 Web 优先断言。
🌐 This method does not wait for the element to pass actionability checks and therefore can lead to the flaky tests. Use Locator.evaluate(), other Locator helper methods or web-first assertions instead.
该方法在页面中查找与指定选择器匹配的元素,并将其作为第一个参数传递给 expression。如果没有元素匹配选择器,该方法会抛出错误。返回 expression 的值。
🌐 The method finds an element matching the specified selector within the page and passes it as a first argument to expression. If no elements match the selector, the method throws an error. Returns the value of expression.
如果 expression 返回一个 Promise,那么 Page.evalOnSelector() 会等待该 promise 解决并返回其值。
🌐 If expression returns a Promise, then Page.evalOnSelector() would wait for the promise to resolve and return its value.
用法
String searchValue = (String) page.evalOnSelector("#search", "el => el.value");
String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href");
String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");
参数
-
要查询的选择器。
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
-
optionsPage.EvalOnSelectorOptions(optional)
返回
evalOnSelectorAll
Added in: v1.9在大多数情况下,Locator.evaluateAll()、其他 Locator 辅助方法以及以网页为先的断言效果更好。
🌐 In most cases, Locator.evaluateAll(), other Locator helper methods and web-first assertions do a better job.
该方法会在页面中查找与指定选择器匹配的所有元素,并将匹配元素的数组作为第一个参数传递给 expression。返回 expression 调用的结果。
🌐 The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. Returns the result of expression invocation.
如果 expression 返回一个 Promise,那么 Page.evalOnSelectorAll() 会等待该 promise 解决并返回其值。
🌐 If expression returns a Promise, then Page.evalOnSelectorAll() would wait for the promise to resolve and return its value.
用法
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);
参数
-
要查询的选择器。
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
fill
Added before v1.9请改为使用基于定位器的 Locator.fill()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.fill() instead. Read more about locators.
此方法会等待匹配 selector 的元素,等待 actionability 检查,聚焦该元素,填写内容,并在填写后触发 input 事件。请注意,你可以传入一个空字符串来清空输入字段。
🌐 This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.
如果目标元素不是 <input>、<textarea> 或 [contenteditable] 元素,该方法会抛出错误。不过,如果该元素位于具有关联 控件 的 <label> 元素内,则会填充控件。
🌐 If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.
要发送细粒度的键盘事件,请使用 Locator.pressSequentially()。
🌐 To send fine-grained keyboard events, use Locator.pressSequentially().
用法
Page.fill(selector, value);
Page.fill(selector, value, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
为
<input>、<textarea>或[contenteditable]元素填写的值。 -
optionsPage.FillOptions(optional)-
setForceboolean (optional) Added in: v1.13#是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
focus
Added before v1.9请改为使用基于定位器的 Locator.focus()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.focus() instead. Read more about locators.
此方法获取一个带有 selector 的元素并将其聚焦。如果没有匹配 selector 的元素,该方法将一直等待直到 DOM 中出现匹配的元素。
🌐 This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.
用法
Page.focus(selector);
Page.focus(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.FocusOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
getAttribute
Added before v1.9请改用基于定位器的 Locator.getAttribute()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.getAttribute() instead. Read more about locators.
返回元素属性值。
🌐 Returns element attribute value.
用法
Page.getAttribute(selector, name);
Page.getAttribute(selector, name, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
要获取其值的属性名称。
-
optionsPage.GetAttributeOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
hover
Added before v1.9请改为使用基于定位器的 Locator.hover()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.hover() instead. Read more about locators.
此方法通过执行以下步骤,将鼠标悬停在匹配 selector 的元素上:
🌐 This method hovers over an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 等待对匹配元素的 actionability 检查,除非已设置 setForce 选项。如果在检查期间元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 将鼠标悬停在元素的中心,或指定的 setPosition 位置。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
Page.hover(selector);
Page.hover(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.HoverOptions(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
setModifiersList<enum KeyboardModifier { ALT, CONTROL, CONTROLORMETA, META, SHIFT }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
setNoWaitAfterboolean (optional) Added in: v1.28#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setPositionPosition (optional)#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
innerHTML
Added before v1.9请改为使用基于定位器的 Locator.innerHTML()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.innerHTML() instead. Read more about locators.
返回 element.innerHTML。
🌐 Returns element.innerHTML.
用法
Page.innerHTML(selector);
Page.innerHTML(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.InnerHTMLOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
innerText
Added before v1.9请改为使用基于定位器的 Locator.innerText()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.innerText() instead. Read more about locators.
返回 element.innerText。
🌐 Returns element.innerText.
用法
Page.innerText(selector);
Page.innerText(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.InnerTextOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
inputValue
Added in: v1.13请改为使用基于定位器的 Locator.inputValue()。阅读更多关于 定位器 的信息。
🌐 Use locator-based Locator.inputValue() instead. Read more about locators.
对于选中的 <input>、<textarea> 或 <select> 元素,返回 input.value。
🌐 Returns input.value for the selected <input> or <textarea> or <select> element.
针对非输入元素会抛出异常。然而,如果该元素位于具有关联控件的 <label> 元素内,则返回该控件的值。
🌐 Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.
用法
Page.inputValue(selector);
Page.inputValue(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.InputValueOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
isChecked
Added before v1.9请改为使用基于定位器的 Locator.isChecked()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.isChecked() instead. Read more about locators.
返回元素是否被选中。如果元素不是复选框或单选按钮,将抛出异常。
🌐 Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
用法
Page.isChecked(selector);
Page.isChecked(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsCheckedOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
isDisabled
Added before v1.9请改为使用基于定位器的 Locator.isDisabled()。阅读更多关于 定位器 的信息。
🌐 Use locator-based Locator.isDisabled() instead. Read more about locators.
返回该元素是否被禁用,与enabled相反。
🌐 Returns whether the element is disabled, the opposite of enabled.
用法
Page.isDisabled(selector);
Page.isDisabled(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsDisabledOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
isEditable
Added before v1.9请改为使用基于定位器的 Locator.isEditable()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.isEditable() instead. Read more about locators.
返回元素是否可编辑。
🌐 Returns whether the element is editable.
用法
Page.isEditable(selector);
Page.isEditable(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsEditableOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
isEnabled
Added before v1.9请改为使用基于定位器的 Locator.isEnabled()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.isEnabled() instead. Read more about locators.
返回元素是否已启用。
🌐 Returns whether the element is enabled.
用法
Page.isEnabled(selector);
Page.isEnabled(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsEnabledOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
isHidden
Added before v1.9请改用基于定位器的 Locator.isHidden()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.isHidden() instead. Read more about locators.
返回元素是否被隐藏,与visible相反。不匹配任何元素的selector也被视为隐藏。
🌐 Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.
用法
Page.isHidden(selector);
Page.isHidden(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsHiddenOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。Page.isHidden() 不会等待元素隐藏,会立即返回。
-
返回
isVisible
Added before v1.9请改为使用基于定位器的 Locator.isVisible()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.isVisible() instead. Read more about locators.
🌐 Returns whether the element is visible. selector that does not match any elements is considered not visible.
用法
Page.isVisible(selector);
Page.isVisible(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.IsVisibleOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。Page.isVisible() 不会等待元素变为可见,并会立即返回。
-
返回
press
Added before v1.9请改为使用基于定位器的 Locator.press()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.press() instead. Read more about locators.
聚焦元素,然后使用 Keyboard.down() 和 Keyboard.up()。
🌐 Focuses the element, and then uses Keyboard.down() and Keyboard.up().
key 可以指定预期的 keyboardEvent.key 值或用于生成文本的单个字符。key 值的超集可以在 这里 找到。键的示例有:
F1 - F12、Digit0- Digit9、KeyA- KeyZ、Backquote、Minus、Equal、Backslash、Backspace、Tab、Delete、Escape、ArrowDown、End、Enter、Home、Insert、PageDown、PageUp、ArrowRight、ArrowUp,等等。
以下修改快捷键也受支持:Shift、Control、Alt、Meta、ShiftLeft、ControlOrMeta。ControlOrMeta 在 Windows 和 Linux 上解析为 Control,在 macOS 上解析为 Meta。
🌐 Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.
按住 Shift 将会输入与大写形式的 key 对应的文本。
🌐 Holding down Shift will type the text that corresponds to the key in the upper case.
如果 key 是单个字符,则区分大小写,因此值 a 和 A 会生成不同的文本。
🌐 If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.
也支持诸如 key: "Control+o"、key: "Control++ 或 key: "Control+Shift+T" 之类的快捷键。当与修饰键一起指定时,在按下后续按键的同时按住修饰键。
🌐 Shortcuts such as key: "Control+o", key: "Control++ or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
用法
Page page = browser.newPage();
page.navigate("https://keycode.info");
page.press("body", "A");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
page.press("body", "ArrowLeft");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" )));
page.press("body", "Shift+O");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
输入按键名称或生成字符名称,如“ArrowLeft”或“a”。
-
optionsPage.PressOptions(optional)-
keydown和keyup之间的等待时间,以毫秒为单位。默认值为 0。 -
setNoWaitAfterboolean (optional)#已弃用该选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
querySelector
Added in: v1.9请改用基于定位器的 Page.locator()。了解更多关于 定位器 的信息。
🌐 Use locator-based Page.locator() instead. Read more about locators.
该方法会在页面中查找与指定选择器匹配的元素。如果没有元素匹配该选择器,返回值将解析为 null。要在页面上等待某个元素,请使用 Locator.waitFor()。
🌐 The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null. To wait for an element on the page, use Locator.waitFor().
用法
Page.querySelector(selector);
Page.querySelector(selector, options);
参数
-
要查询的选择器。
-
optionsPage.QuerySelectorOptions(optional)
返回
querySelectorAll
Added in: v1.9请改用基于定位器的 Page.locator()。了解更多关于 定位器 的信息。
🌐 Use locator-based Page.locator() instead. Read more about locators.
该方法会查找页面中所有匹配指定选择器的元素。如果没有元素匹配该选择器,返回值将解析为 []。
🌐 The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].
用法
Page.querySelectorAll(selector);
参数
返回
selectOption
Added before v1.9请改用基于定位器的 Locator.selectOption()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.selectOption() instead. Read more about locators.
该方法等待匹配selector(/api/class-page.mdx#page-select-option-option-selector)的元素,等待[可作性](../actionability.mdx)检查,等待所有指定选项都包含在 <select> 元素中,然后选择这些选项。
🌐 This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.
如果目标元素不是 <select> 元素,此方法将抛出错误。然而,如果该元素位于具有关联 控件 的 <label> 元素内,则会使用该控件。
🌐 If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.
返回已成功选择的选项值的数组。
🌐 Returns the array of option values that have been successfully selected.
在所有提供的选项都被选择后,触发 change 和 input 事件。
🌐 Triggers a change and input event once all the provided options have been selected.
用法
// Single selection matching the value or label
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
valuesnull | String | ElementHandle | String[] |SelectOption| ElementHandle[] |SelectOption[]#-
setValueString (optional)比赛由“option.value”统计。可选。
-
setLabelString (optional)由
option.label匹配。可选。 -
setIndexint (optional)按索引匹配。可选。
可选择的选项。如果
<select>拥有multiple属性,则所有匹配的选项都会被选中,否则只会选择与传入选项之一匹配的第一个选项。字符串值会同时匹配值和标签。如果所有指定的属性都匹配,则该选项被视为匹配。 -
-
optionsPage.SelectOptionOptions(optional)-
setForceboolean (optional) Added in: v1.13#是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
setChecked
Added in: v1.15请改为使用基于定位器的 Locator.setChecked()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.setChecked() instead. Read more about locators.
此方法通过执行以下步骤来勾选或取消勾选与 selector 匹配的元素:
🌐 This method checks or unchecks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 确保匹配的元素是复选框或单选按钮。如果不是,该方法将抛出异常。
- 如果元素已经具有正确的检查状态,则此方法立即返回。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 在元素中心点击。
- 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时时间将禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
Page.setChecked(selector, checked);
Page.setChecked(selector, checked, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否选中或取消选中复选框。
-
optionsPage.SetCheckedOptions(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setPositionPosition (optional)#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
setInputFiles
Added before v1.9请改用基于定位器的 Locator.setInputFiles()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.setInputFiles() instead. Read more about locators.
将文件输入的值设置为这些文件路径或文件。如果某些 filePaths 是相对路径,则相对于当前工作目录进行解析。对于空数组,会清除选中的文件。对于带有 [webkitdirectory] 属性的输入,只支持单个目录路径。
🌐 Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a [webkitdirectory] attribute, only a single directory path is supported.
此方法期望 selector 指向一个 输入元素。但是,如果该元素位于具有相关 控件 的 <label> 元素内,则会改为定位该控件。
🌐 This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.
用法
Page.setInputFiles(selector, files);
Page.setInputFiles(selector, files, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.SetInputFilesOptions(optional)-
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
tap
Added before v1.9请改为使用基于定位器的 Locator.tap()。了解更多关于 定位器 的信息。
🌐 Use locator-based Locator.tap() instead. Read more about locators.
此方法通过执行以下步骤来点击匹配 selector 的元素:
🌐 This method taps an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.touchscreen() 点击元素的中心,或指定的 setPosition 位置。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时时间将禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
Page.tap() 方法将在浏览器上下文的 setHasTouch 选项为 false 时抛出异常。:::
用法
Page.tap(selector);
Page.tap(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.TapOptions(optional)
此选项无效。
-
setPositionPosition (optional)#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
返回
textContent
Added before v1.9请改为使用基于定位器的 Locator.textContent()。阅读更多关于 定位器 的内容。
🌐 Use locator-based Locator.textContent() instead. Read more about locators.
返回 element.textContent。
🌐 Returns element.textContent.
用法
Page.textContent(selector);
Page.textContent(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.TextContentOptions(optional)-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
type
Added before v1.9在大多数情况下,你应使用 Locator.fill()。只有在页面上有特殊键盘处理时,才需要逐个按键—在这种情况下使用 Locator.pressSequentially()。
🌐 In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.pressSequentially().
对文本中的每个字符发送 keydown、keypress/input 和 keyup 事件。page.type 可用于发送更精细的键盘事件。要在表单字段中填充值,请使用 Page.fill()。
🌐 Sends a keydown, keypress/input, and keyup event for each character in the text. page.type can be used to send fine-grained keyboard events. To fill values in form fields, use Page.fill().
要按特殊按键,如“Control”或“ArrowDown”,请使用[Keyboard.press()](/api/class-keyboard.mdx#keyboard-press)。
🌐 To press a special key, like Control or ArrowDown, use Keyboard.press().
用法
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
要输入到焦点元素中的文本。
-
optionsPage.TypeOptions(optional)-
按键之间的等待时间,以毫秒为单位。默认为 0。
-
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
uncheck
Added before v1.9请改为使用基于定位器的 Locator.uncheck()。阅读更多关于 定位器 的信息。
🌐 Use locator-based Locator.uncheck() instead. Read more about locators.
此方法通过执行以下步骤取消选中与 selector 匹配的元素:
🌐 This method unchecks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 确保匹配的元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经未选中,该方法会立即返回。
- 等待匹配元素的 actionability 检查,除非设置了 setForce 选项。如果元素在检查过程中被移除,整个操作将会重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.mouse() 在元素中心点击。
- 确保该元素现在未被选中。如果不是,这种方法会抛出异常。
当所有步骤在指定的 setTimeout 内未完成时,该方法会抛出 TimeoutError。传入零超时时间将禁用此功能。
🌐 When all steps combined have not finished during the specified setTimeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
Page.uncheck(selector);
Page.uncheck(selector, options);
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
optionsPage.UncheckOptions(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
setNoWaitAfterboolean (optional)#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
setPositionPosition (optional) Added in: v1.11#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setTrialboolean (optional) Added in: v1.11#设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
waitForNavigation
Added before v1.9这种方法本质上带有大胆性质,请改用[Page.waitForURL()](/api/class-page.mdx#page-wait-for-url)。
🌐 This method is inherently racy, please use Page.waitForURL() instead.
等待主框架导航并返回主资源响应。如果发生多次重定向,导航将以最后一次重定向的响应作为结果。如果导航到不同的锚点或由于使用 History API 导致导航,导航将以 null 作为结果。
🌐 Waits for the main frame navigation and returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with null.
用法
当页面导航到新网址或重新加载时,这个问题就会解决。当你运行可能间接导致页面导航的代码时,这个方法很有用。例如,点击目标有一个 onclick 处理器,它会从 setTimeout 触发导航。请看这个例子:
🌐 This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. e.g. The click target has an onclick handler that triggers navigation from a setTimeout. Consider this example:
// The method returns after navigation has finished
Response response = page.waitForNavigation(() -> {
// This action triggers the navigation after a timeout.
page.getByText("Navigate after timeout").click();
});
使用 History API 更改 URL 被视为一次导航。
参数
-
optionsPage.WaitForNavigationOptions(optional)-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultNavigationTimeout()、BrowserContext.setDefaultTimeout()、Page.setDefaultNavigationTimeout() 或 Page.setDefaultTimeout() 方法进行更改。 -
setUrlString | Pattern | Predicate<String> (optional)#一个通配符模式、正则表达式模式或接收 [URL] 的谓词,用于在等待导航时进行匹配。请注意,如果参数是没有通配符字符的字符串,该方法将等待导航到与该字符串完全相同的 URL。
-
setWaitUntilenum WaitUntilState { LOAD, DOMCONTENTLOADED, NETWORKIDLE, COMMIT }(optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
-
-
callbackRunnable Added in: v1.9#执行触发事件的操作的回调。
返回
waitForSelector
Added before v1.9改用断言网页元素可见性的 Web 断言,或基于定位器的 Locator.waitFor()。阅读更多关于 定位器 的内容。
🌐 Use web assertions that assert visibility or a locator-based Locator.waitFor() instead. Read more about locators.
当由选择器指定的元素满足 setState 选项时返回。如果等待 hidden 或 detached,则返回 null。
🌐 Returns when element specified by selector satisfies setState option. Returns null if waiting for hidden or detached.
等待 selector 满足 setState 选项(要么从 DOM 中出现/消失,要么变为可见/隐藏)。如果在调用该方法时 selector 已经满足条件,该方法将立即返回。如果选择器在 setTimeout 毫秒内未满足条件,函数将抛出异常。
🌐 Wait for the selector to satisfy setState option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the setTimeout milliseconds, the function will throw.
用法
此方法适用于多种导航:
🌐 This method works across navigations:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch();
Page page = browser.newPage();
for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) {
page.navigate(currentURL);
ElementHandle element = page.waitForSelector("img");
System.out.println("Loaded image: " + element.getAttribute("src"));
}
browser.close();
}
}
}
参数
-
要查询的选择器。
-
optionsPage.WaitForSelectorOptions(optional)-
setStateenum WaitForSelectorState { ATTACHED, DETACHED, VISIBLE, HIDDEN }(optional)#默认值为
'visible'。可以是以下之一:'attached'- 等待元素出现在 DOM 中。'detached'- 等待元素不再出现在 DOM 中。'visible'- 等待元素有非空的边界框并且不含visibility:hidden。请注意,没有任何内容或含有display:none的元素会有空的边界框,并且不被认为是可见的。'hidden'- 等待元素被从 DOM 中移除,或其边界框为空,或为visibility:hidden。这与'visible'选项相反。
-
setStrictboolean (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.setDefaultTimeout() 或 Page.setDefaultTimeout() 方法进行更改。
-
返回
waitForTimeout
Added before v1.9在生产环境中永远不要等待超时。等待时间的测试本质上是不稳定的。应使用[定位器]操作和自动等待的网页断言。
🌐 Never wait for timeout in production. Tests that wait for time are inherently flaky. Use Locator actions and web assertions that wait automatically.
等待指定的 timeout 毫秒。
🌐 Waits for the given timeout in milliseconds.
请注意,page.waitForTimeout() 应仅用于调试。在生产环境中使用计时器进行测试可能会不稳定。请改用网络事件、选择器可见性等信号。
🌐 Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
用法
// wait for 1 second
page.waitForTimeout(1000);
参数
返回