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:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch()
context = browser.new_context()
page = context.new_page()
page.goto("https://example.com")
page.screenshot(path="screenshot.png")
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch()
context = await browser.new_context()
page = await context.new_page()
await page.goto("https://example.com")
await page.screenshot(path="screenshot.png")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
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.once("load", lambda: print("page loaded!"))
要取消订阅事件,请使用 removeListener 方法:
🌐 To unsubscribe from events use the removeListener method:
def log_request(intercepted_request):
print("a request was made:", intercepted_request.url)
page.on("request", log_request)
# sometime later...
page.remove_listener("request", log_request)
方法
🌐 Methods
add_init_script
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;
- Sync
- Async
# in your playwright script, assuming the preload.js file is in same directory
page.add_init_script(path="./preload.js")
# in your playwright script, assuming the preload.js file is in same directory
await page.add_init_script(path="./preload.js")
通过 browser_context.add_init_script() 和 page.add_init_script() 安装的多个脚本的执行顺序未定义。
🌐 The order of evaluation of multiple scripts installed via browser_context.add_init_script() and page.add_init_script() is not defined.
参数
-
pathUnion[str, pathlib.Path] (optional)#JavaScript 文件的路径。如果
path是相对路径,则相对于当前工作目录解析。可选。 -
在浏览器上下文中对所有页面执行的脚本。可选。
返回
add_locator_handler
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.add_locator_handler()](/api/class-page.mdx#page-add-locator-handler)。
- 在执行或重试需要进行可操作性检查的操作之前,或者在执行自动等待断言检查之前,Playwright 会每次检查覆盖层是否存在。当覆盖层可见时,Playwright 会先调用处理程序,然后再继续执行操作或断言。请注意,只有在执行操作或断言时才会调用该处理程序——如果覆盖层变为可见但你没有执行任何操作,处理程序将不会被触发。
- 在执行处理程序后,Playwright 将确保触发该处理程序的覆盖层不再可见。你可以通过 no_wait_after 选择退出此行为。
- 处理程序的执行时间计入执行该处理程序的动作/断言的超时。如果你的处理程序运行时间过长,可能会导致超时。
- 你可以注册多个处理程序,但同一时间只会运行一个处理程序。确保处理程序中的操作不依赖于其他处理程序。
运行处理程序会在测试中途更改页面状态。例如,它会更改当前聚焦的元素并移动鼠标。确保在处理程序之后执行的操作是自包含的,并且不依赖于焦点和鼠标状态保持不变。
🌐 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:
- Sync
- Async
# Setup the handler.
def handler():
page.get_by_role("button", name="No thanks").click()
page.add_locator_handler(page.get_by_text("Sign up to the newsletter"), handler)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.get_by_role("button", name="No thanks").click()
await page.add_locator_handler(page.get_by_text("Sign up to the newsletter"), handler)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
一个在显示“确认你的安全详情”页面时跳过该页面的示例:
🌐 An example that skips the "Confirm your security details" page when it is shown:
- Sync
- Async
# Setup the handler.
def handler():
page.get_by_role("button", name="Remind me later").click()
page.add_locator_handler(page.get_by_text("Confirm your security details"), handler)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.get_by_role("button", name="Remind me later").click()
await page.add_locator_handler(page.get_by_text("Confirm your security details"), handler)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
这是一个在每次可操作性检查时使用自定义回调的示例。它使用一个总是可见的 <body> 定位器,因此在每次可操作性检查之前都会调用该处理程序。指定 no_wait_after 很重要,因为该处理程序不会隐藏 <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 no_wait_after, because the handler does not hide the <body> element.
- Sync
- Async
# Setup the handler.
def handler():
page.evaluate("window.removeObstructionsForTestIfNeeded()")
page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
# Write the test as usual.
page.goto("https://example.com")
page.get_by_role("button", name="Start here").click()
# Setup the handler.
async def handler():
await page.evaluate("window.removeObstructionsForTestIfNeeded()")
await page.add_locator_handler(page.locator("body"), handler, no_wait_after=True)
# Write the test as usual.
await page.goto("https://example.com")
await page.get_by_role("button", name="Start here").click()
处理程序将原始定位器作为参数。你还可以通过设置 times 在调用若干次后自动移除处理程序:
🌐 Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting times:
- Sync
- Async
def handler(locator):
locator.click()
page.add_locator_handler(page.get_by_label("Close"), handler, times=1)
async def handler(locator):
await locator.click()
await page.add_locator_handler(page.get_by_label("Close"), handler, times=1)
参数
-
触发处理程序的定位器。
-
handlerCallable[Locator]:Promise[Any]#当 locator 出现时应运行的函数。该函数应移除阻碍点击等操作的元素。
-
no_wait_afterbool (optional) Added in: v1.44#默认情况下,调用处理程序后,Playwright 会等待覆盖层隐藏,然后才会继续执行触发处理程序的操作/断言。此选项允许选择退出此行为,以便处理程序运行后覆盖层仍然保持可见。
-
timesint (optional) Added in: v1.44#指定此处理程序应被调用的最大次数。默认情况下为无限制。
返回
add_script_tag
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.add_script_tag()
page.add_script_tag(**kwargs)
参数
-
要注入到框架中的原始 JavaScript 内容。
-
pathUnion[str, pathlib.Path] (optional)#要注入到框架中的 JavaScript 文件路径。如果
path是相对路径,则相对于当前工作目录解析。 -
脚本类型。使用 'module' 来加载 JavaScript ES6 模块。更多详情请参见 script。
-
要添加的脚本的 URL。
返回
add_style_tag
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.add_style_tag()
page.add_style_tag(**kwargs)
参数
-
要注入到框架中的原始 CSS 内容。
-
pathUnion[str, pathlib.Path] (optional)#要注入到框架中的 CSS 文件路径。如果
path是相对路径,则相对于当前工作目录解析。 -
<link>标签的 URL。
返回
bring_to_front
Added before v1.9将页面置于前面(激活选项卡)。
🌐 Brings page to front (activates tab).
用法
page.bring_to_front()
返回
close
Added before v1.9如果 run_before_unload 是 false,则不会执行任何卸载处理程序,并会等待页面关闭。如果 run_before_unload 是 true,该方法会运行卸载处理程序,但不会等待页面关闭。
🌐 If run_before_unload is false, does not run any unload handlers and waits for the page to be closed. If run_before_unload 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.
如果将 run_before_unload 设置为 true,可能会弹出一个 beforeunload 对话框,并且应通过 page.on("dialog") 事件手动处理。
🌐 if run_before_unload is passed as true, a beforeunload dialog might be summoned and should be handled manually via page.on("dialog") event.
用法
page.close()
page.close(**kwargs)
参数
-
reasonstr (optional) Added in: v1.40#报告因页面关闭而中断的操作的原因。
-
run_before_unloadbool (optional)#默认为
false。是否运行 before unload 页面处理程序。
返回
console_messages
Added in: v1.56返回此页面最多(当前)200条最近的控制台消息。更多详情请参见 page.on("console")。
🌐 Returns up to (currently) 200 last console messages from this page. See page.on("console") for more details.
用法
page.console_messages()
返回
content
Added before v1.9获取页面的完整 HTML 内容,包括文档类型。
🌐 Gets the full HTML contents of the page, including the doctype.
用法
page.content()
返回
drag_and_drop
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.
用法
- Sync
- Async
page.drag_and_drop("#source", "#target")
# or specify exact positions relative to the top-left corners of the elements:
page.drag_and_drop(
"#source",
"#target",
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
await page.drag_and_drop("#source", "#target")
# or specify exact positions relative to the top-left corners of the elements:
await page.drag_and_drop(
"#source",
"#target",
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
参数
-
用于搜索要拖动的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
用于搜索要放置的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
source_positionDict (optional) Added in: v1.14#在此位置点击源元素,相对于元素内边距框的左上角。如果未指定,则使用元素的某个可见点。
-
stepsint (optional) Added in: v1.57#默认为 1。发送
n个插值的mousemove事件以表示拖动的mousedown和mouseup之间的移动。当设置为 1 时,在目标位置仅触发一个mousemove事件。 -
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
target_positionDict (optional) Added in: v1.14#在此点相对于元素填充框左上角投放目标元素。如果未指定,则使用元素的某个可见点。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
返回
emulate_media
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.
用法
- Sync
- Async
page.evaluate("matchMedia('screen').matches")
# → True
page.evaluate("matchMedia('print').matches")
# → False
page.emulate_media(media="print")
page.evaluate("matchMedia('screen').matches")
# → False
page.evaluate("matchMedia('print').matches")
# → True
page.emulate_media()
page.evaluate("matchMedia('screen').matches")
# → True
page.evaluate("matchMedia('print').matches")
# → False
await page.evaluate("matchMedia('screen').matches")
# → True
await page.evaluate("matchMedia('print').matches")
# → False
await page.emulate_media(media="print")
await page.evaluate("matchMedia('screen').matches")
# → False
await page.evaluate("matchMedia('print').matches")
# → True
await page.emulate_media()
await page.evaluate("matchMedia('screen').matches")
# → True
await page.evaluate("matchMedia('print').matches")
# → False
- Sync
- Async
page.emulate_media(color_scheme="dark")
page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")
# → True
page.evaluate("matchMedia('(prefers-color-scheme: light)').matches")
# → False
await page.emulate_media(color_scheme="dark")
await page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches")
# → True
await page.evaluate("matchMedia('(prefers-color-scheme: light)').matches")
# → False
参数
-
color_scheme"light" | "dark" | "no-preference" | "null" (optional) Added in: v1.9#模拟 prefers-colors-scheme 媒体特性,支持的值为
'light'和'dark'。传入'Null'可禁用配色方案模拟。'no-preference'已被弃用。 -
contrast"no-preference" | "more" | "null" (optional) Added in: v1.51# -
forced_colors"active" | "none" | "null" (optional) Added in: v1.15# -
media"screen" | "print" | "null" (optional) Added in: v1.9#更改页面的 CSS 媒体类型。唯一允许的值是
'Screen'、'Print'和'Null'。传递'Null'会禁用 CSS 媒体模拟。 -
reduced_motion"reduce" | "no-preference" | "null" (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:
- Sync
- Async
result = page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
print(result) # prints "56"
result = await page.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
print(result) # prints "56"
也可以传入字符串而不是函数:
🌐 A string can also be passed in instead of a function:
- Sync
- Async
print(page.evaluate("1 + 2")) # prints "3"
x = 10
print(page.evaluate(f"1 + {x}")) # prints "11"
print(await page.evaluate("1 + 2")) # prints "3"
x = 10
print(await page.evaluate(f"1 + {x}")) # prints "11"
ElementHandle 实例可以作为参数传递给 page.evaluate():
- Sync
- Async
body_handle = page.evaluate("document.body")
html = page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
body_handle.dispose()
body_handle = await page.evaluate("document.body")
html = await page.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
await body_handle.dispose()
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
evaluate_handle
Added before v1.9以 JSHandle 的形式返回 expression 调用的值。
🌐 Returns the value of the expression invocation as a JSHandle.
page.evaluate() 和 page.evaluate_handle() 唯一的区别是 page.evaluate_handle() 返回 JSHandle。
🌐 The only difference between page.evaluate() and page.evaluate_handle() is that page.evaluate_handle() returns JSHandle.
如果传递给 page.evaluate_handle() 的函数返回一个 Promise,那么 page.evaluate_handle() 会等待该 promise 解决并返回其值。
🌐 If the function passed to the page.evaluate_handle() returns a Promise, then page.evaluate_handle() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
a_window_handle = page.evaluate_handle("Promise.resolve(window)")
a_window_handle # handle for the window object.
a_window_handle = await page.evaluate_handle("Promise.resolve(window)")
a_window_handle # handle for the window object.
也可以传入字符串而不是函数:
🌐 A string can also be passed in instead of a function:
- Sync
- Async
a_handle = page.evaluate_handle("document") # handle for the "document"
a_handle = await page.evaluate_handle("document") # handle for the "document"
JSHandle 实例可以作为参数传递给 page.evaluate_handle():
- Sync
- Async
a_handle = page.evaluate_handle("document.body")
result_handle = page.evaluate_handle("body => body.innerHTML", a_handle)
print(result_handle.json_value())
result_handle.dispose()
a_handle = await page.evaluate_handle("document.body")
result_handle = await page.evaluate_handle("body => body.innerHTML", a_handle)
print(await result_handle.json_value())
await result_handle.dispose()
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
expect_console_message
Added in: v1.9执行操作并等待页面中记录 ConsoleMessage。如果提供了谓词,会将 ConsoleMessage 值传入 predicate 函数,并等待 predicate(message) 返回真值。如果在 page.on("console") 事件触发之前页面被关闭,将抛出错误。
🌐 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.on("console") event is fired.
用法
page.expect_console_message()
page.expect_console_message(**kwargs)
参数
-
predicateCallable[ConsoleMessage]:bool (optional)#接收 ConsoleMessage 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_download
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.expect_download()
page.expect_download(**kwargs)
参数
-
predicateCallable[Download]:bool (optional)#接收 Download 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_event
Added before v1.9等待事件触发并将其值传递给谓词函数。当谓词返回真值时返回。如果在事件触发前页面被关闭,将抛出错误。返回事件数据的值。
🌐 Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the page is closed before the event is fired. Returns the event data value.
用法
- Sync
- Async
with page.expect_event("framenavigated") as event_info:
page.get_by_role("button")
frame = event_info.value
async with page.expect_event("framenavigated") as event_info:
await page.get_by_role("button")
frame = await event_info.value
参数
-
事件名称,通常传递到
*.on(event)的那个相同名称。 -
predicateCallable (optional)#接收事件数据并在等待解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_file_chooser
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.expect_file_chooser()
page.expect_file_chooser(**kwargs)
参数
-
predicateCallable[FileChooser]:bool (optional)#接收 FileChooser 对象,并在等待应被解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_popup
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.expect_popup()
page.expect_popup(**kwargs)
参数
-
predicateCallable[Page]:bool (optional)#接收 Page 对象,并在等待条件应该满足时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_request
Added before v1.9等待匹配的请求并返回它。有关事件的更多详细信息,请参见等待事件。
🌐 Waits for the matching request and returns it. See waiting for event for more details about events.
用法
- Sync
- Async
with page.expect_request("http://example.com/resource") as first:
page.get_by_text("trigger request").click()
first_request = first.value
# or with a lambda
with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
page.get_by_text("trigger request").click()
second_request = second.value
async with page.expect_request("http://example.com/resource") as first:
await page.get_by_text("trigger request").click()
first_request = await first.value
# or with a lambda
async with page.expect_request(lambda request: request.url == "http://example.com" and request.method == "get") as second:
await page.get_by_text("trigger request").click()
second_request = await second.value
参数
-
url_or_predicatestr | Pattern | Callable[Request]:bool#请求 URL 字符串、正则表达式或接收 Request 对象的断言。当通过上下文选项提供了 base_url 并且传入的 URL 是一个路径时,它会通过
new URL()构造函数进行合并。 -
最大等待时间(以毫秒为单位),默认值为 30 秒,传入
0可禁用超时。默认值可以通过使用 page.set_default_timeout() 方法进行更改。
返回
expect_request_finished
Added in: v1.12执行操作并等待 Request 加载完成。如果提供了谓词,它会将 Request 的值传递给 predicate 函数,并等待 predicate(request) 返回一个真值。如果在触发 page.on("requestfinished") 事件之前页面被关闭,将抛出错误。
🌐 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.on("requestfinished") event is fired.
用法
page.expect_request_finished()
page.expect_request_finished(**kwargs)
参数
-
predicateCallable[Request]:bool (optional)#接收 Request 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_response
Added before v1.9返回匹配的响应。有关事件的更多详细信息,请参阅等待事件。
🌐 Returns the matched response. See waiting for event for more details about events.
用法
- Sync
- Async
with page.expect_response("https://example.com/resource") as response_info:
page.get_by_text("trigger response").click()
response = response_info.value
return response.ok
# or with a lambda
with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200 and response.request.method == "get") as response_info:
page.get_by_text("trigger response").click()
response = response_info.value
return response.ok
async with page.expect_response("https://example.com/resource") as response_info:
await page.get_by_text("trigger response").click()
response = await response_info.value
return response.ok
# or with a lambda
async with page.expect_response(lambda response: response.url == "https://example.com" and response.status == 200 and response.request.method == "get") as response_info:
await page.get_by_text("trigger response").click()
response = await response_info.value
return response.ok
参数
-
url_or_predicatestr | Pattern | Callable[Response]:bool#请求 URL 字符串、正则表达式或接收 Response 对象的断言。当通过上下文选项提供了 base_url 并且传入的 URL 是一个路径时,它会通过
new URL()构造函数进行合并。 -
最大等待时间以毫秒计,默认为30秒,通过“0”禁用超时。默认值可以通过使用 [browser_context.set_default_timeout()]](/api/class-browsercontext.mdx#browser-context-set-default-timeout) 或 [page.set_default_timeout()](/api/class-page.mdx#page-set-default-timeout) 方法来更改。
返回
expect_websocket
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.expect_websocket()
page.expect_websocket(**kwargs)
参数
-
predicateCallable[WebSocket]:bool (optional)#接收 WebSocket 对象,并在等待应被解决时返回真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expect_worker
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.expect_worker()
page.expect_worker(**kwargs)
参数
-
predicateCallable[Worker]:bool (optional)#接收 Worker 对象,并在等待应当解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
expose_binding
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 }.
有关上下文范围版本,请参见 browser_context.expose_binding()。
🌐 See browser_context.expose_binding() for the context-wide version.
通过 page.expose_binding() 安装的函数在页面导航后仍然存在。
🌐 Functions installed via page.expose_binding() survive navigations.
用法
向页面中的所有框架公开页面 URL 的示例:
🌐 An example of exposing page URL to all frames in a page:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.expose_binding("pageURL", lambda source: source["page"].url)
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.click("button")
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=False)
context = await browser.new_context()
page = await context.new_page()
await page.expose_binding("pageURL", lambda source: source["page"].url)
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.click("button")
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
参数
-
窗口对象上的函数名称。
-
将在 Playwright 上下文中调用的回调函数。
-
已弃用
此选项将在未来被移除。
是否将参数作为句柄传递,而不是按值传递。传递句柄时,只支持一个参数。按值传递时,支持多个参数。
返回
expose_function
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.
有关上下文范围内暴露的函数,请参阅 browser_context.expose_function()。
🌐 See browser_context.expose_function() for context-wide exposed function.
通过 page.expose_function() 安装的函数在页面导航后仍然有效。
🌐 Functions installed via page.expose_function() survive navigations.
用法
在页面中添加 sha256 函数的示例:
🌐 An example of adding a sha256 function to the page:
- Sync
- Async
import hashlib
from playwright.sync_api import sync_playwright, Playwright
def sha256(text):
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
page = browser.new_page()
page.expose_function("sha256", sha256)
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.click("button")
with sync_playwright() as playwright:
run(playwright)
import asyncio
import hashlib
from playwright.async_api import async_playwright, Playwright
def sha256(text):
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=False)
page = await browser.new_page()
await page.expose_function("sha256", sha256)
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.click("button")
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
参数
返回
frame
Added before v1.9返回符合指定条件的帧。必须指定 name 或 url。
🌐 Returns frame matching the specified criteria. Either name or url must be specified.
用法
frame = page.frame(name="frame-name")
frame = page.frame(url=r".*domain.*")
参数
-
在
iframe的name属性中指定的帧名称。可选。 -
urlstr | Pattern | Callable[URL]:bool (optional)#一个全局匹配模式、正则表达式模式或谓词,接收帧的
url作为 URL 对象。可选。
返回
frame_locator
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">:
- Sync
- Async
locator = page.frame_locator("#my-iframe").get_by_text("Submit")
locator.click()
locator = page.frame_locator("#my-iframe").get_by_text("Submit")
await locator.click()
参数
返回
get_by_alt_text
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'>
- Sync
- Async
page.get_by_alt_text("Playwright logo").click()
await page.get_by_alt_text("Playwright logo").click()
参数
-
用于定位元素的文本。
-
是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
get_by_label
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">
- Sync
- Async
page.get_by_label("Username").fill("john")
page.get_by_label("Password").fill("secret")
await page.get_by_label("Username").fill("john")
await page.get_by_label("Password").fill("secret")
参数
-
用于定位元素的文本。
-
是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
get_by_placeholder
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:
- Sync
- Async
page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
await page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
参数
-
用于定位元素的文本。
-
是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
get_by_role
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:
- Sync
- Async
expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
page.get_by_role("checkbox", name="Subscribe").check()
page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
await expect(page.get_by_role("heading", name="Sign up")).to_be_visible()
await page.get_by_role("checkbox", name="Subscribe").check()
await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
参数
-
role"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"#所需的咏叹调角色。
-
通常由
aria-checked或原生<input type=checkbox>控件设置的属性。了解更多关于
aria-checked的信息。 -
通常由
aria-disabled或disabled设置的属性。note与大多数其他属性不同,
disabled是通过 DOM 层级继承的。了解更多关于aria-disabled的信息。 -
exactbool (optional) Added in: v1.28#是否与name完全匹配:区分大小写且匹配整个字符串。默认值为 false。当name 是正则表达式时会被忽略。注意,完全匹配仍会去除空格。
-
通常由
aria-expanded设置的属性。了解更多关于
aria-expanded的信息。 -
include_hiddenbool (optional)#控制是否匹配隐藏元素的选项。默认情况下,角色选择器仅匹配非隐藏元素,由 ARIA 定义。
了解更多关于
aria-hidden的信息。 -
一个通常存在于角色
heading、listitem、row、treeitem的数字属性,对<h1>-<h6>元素有默认值。了解更多关于
aria-level的信息。 -
namestr | Pattern (optional)#选项用于匹配可访问名称。默认情况下,匹配不区分大小写并搜索子字符串,使用精确可以控制此行为。
了解有关可访问名称的更多信息。
-
通常由
aria-pressed设置的属性。了解更多关于
aria-pressed的信息。 -
通常由
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.
get_by_test_id
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:
- Sync
- Async
page.get_by_test_id("directions").click()
await page.get_by_test_id("directions").click()
参数
返回
详情
默认情况下,'data-testid' 属性被用作测试 ID。如有需要,使用 [selectors.set_test_id_attribute()](/api/class-selectors.mdx#selectors-set-test-id-attribute) 配置不同的测试 ID 属性。
🌐 By default, the data-testid attribute is used as a test id. Use selectors.set_test_id_attribute() to configure a different test id attribute if necessary.
get_by_text
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:
- Sync
- Async
# Matches <span>
page.get_by_text("world")
# Matches first <div>
page.get_by_text("Hello world")
# Matches second <div>
page.get_by_text("Hello", exact=True)
# Matches both <div>s
page.get_by_text(re.compile("Hello"))
# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))
# Matches <span>
page.get_by_text("world")
# Matches first <div>
page.get_by_text("Hello world")
# Matches second <div>
page.get_by_text("Hello", exact=True)
# Matches both <div>s
page.get_by_text(re.compile("Hello"))
# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))
参数
-
用于定位元素的文本。
-
是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
详情
文本匹配总是会规范化空白字符,即使是完全匹配。例如,它会将多个空格变为一个,将换行符变为空格,并忽略开头和结尾的空白。
🌐 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">.
get_by_title
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:
- Sync
- Async
expect(page.get_by_title("Issues count")).to_have_text("25 issues")
await expect(page.get_by_title("Issues count")).to_have_text("25 issues")
参数
-
用于定位元素的文本。
-
是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
go_back
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.go_back()
page.go_back(**kwargs)
参数
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
go_forward
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.go_forward()
page.go_forward(**kwargs)
参数
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
goto
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 错误(例如,在自签名证书的情况下)。
- 目标网址无效。
- 在导航过程中超出了超时。
- 远程服务器没有响应或无法访问。
- 主要资源加载失败。
当远程服务器返回任何有效的 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.goto(url)
page.goto(url, **kwargs)
参数
-
要导航到的页面的 URL。URL 应包括协议,例如
https://。当通过上下文选项提供了 base_url 并且传入的 URL 是路径时,它会通过new URL()构造函数合并。 -
Referer 头的值。如果提供,它将优先于由 page.set_extra_http_headers() 设置的 referer 头的值。
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
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, **kwargs)
参数
-
解析 DOM 元素时使用的选择器。
-
将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,
article拥有text=Playwright匹配<article><div>Playwright</div></article>。内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含
div的content,位于<article><content><div>Playwright</div></content></article>中。然而,查找包含article div的content会失败,因为内部定位器必须是相对的,不应使用content之外的任何元素。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
has_notLocator (optional) Added in: v1.33#匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含
div的article会匹配<article><span>Playwright</span></article>。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
has_not_textstr | Pattern (optional) Added in: v1.33#匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入[string]时,匹配不区分大小写,并搜索子字符串。
-
has_textstr | Pattern (optional)#匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,
"Playwright"可以匹配<article><div>Playwright</div></article>。
返回
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()
返回
page_errors
Added in: v1.56返回此页面的最多(当前为)200个最后页面错误。更多详情请参见 page.on("pageerror")。
🌐 Returns up to (currently) 200 last page errors from this page. See page.on("pageerror") for more details.
用法
page.page_errors()
返回
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.
用法
page.pause()
返回
pdf
Added before v1.9返回 PDF 缓冲区。
🌐 Returns the PDF buffer.
page.pdf() 使用 print CSS 媒体生成页面的 PDF。要使用 screen 媒体生成 PDF,请在调用 page.pdf() 之前调用 page.emulate_media() :
默认情况下,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.
用法
- Sync
- Async
# generates a pdf with "screen" media type.
page.emulate_media(media="screen")
page.pdf(path="page.pdf")
# generates a pdf with "screen" media type.
await page.emulate_media(media="screen")
await page.pdf(path="page.pdf")
width、height 和 margin 选项接受带单位的数值。未标注单位的数值将被视为像素。
🌐 The width, height, and margin 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
格式 选项有:
🌐 The format 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 英寸
header_template 和 footer_template 标记存在以下限制: > 1. 模板内部的脚本标签不会被执行。 > 2. 模板内部无法显示页面样式。 :::
参数
-
display_header_footerbool (optional)#显示页眉和页脚。默认为
false。 -
footer_templatestr (optional)#打印页脚的 HTML 模板。应使用与 header_template 相同的格式。
-
header_templatestr (optional)#打印页眉的 HTML 模板。应为有效的 HTML 标记,并使用以下类将打印值注入其中:
'date'格式化打印日期'title'文档标题'url'文档位置'pageNumber'当前页码- 文档中共有
'totalPages'页
-
heightstr | float (optional)#纸张高度,接受标有单位的值。
-
纸张方向。默认为
false。 -
-
上边距,接受带单位的数值。默认值为
0。 -
右边距,接受带单位的数值。默认值为
0。 -
底部边距,接受带单位的数值。默认值为
0。 -
左边距,接受带单位标注的数值。默认值为
0。
纸张边距,默认为无。
-
-
outlinebool (optional) Added in: v1.42#是否将文档大纲嵌入到 PDF 中。默认值为
false。 -
要打印的页码范围,例如,'1-5, 8, 11-13'。默认值为空字符串,表示打印所有页面。
-
pathUnion[str, pathlib.Path] (optional)#保存 PDF 的文件路径。如果 路径 是相对路径,则相对于当前工作目录进行解析。如果未提供路径,PDF 将不会保存到磁盘。
-
prefer_css_page_sizebool (optional)#使页面中声明的任何 CSS
@page大小优先于在 width、height 或 format 选项中声明的设置。默认值为false,它会将内容缩放以适应纸张大小。 -
print_backgroundbool (optional)#打印背景图形。默认为
false。 -
网页渲染的缩放比例。默认为
1。缩放比例必须在 0.1 到 2 之间。 -
taggedbool (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(**kwargs)
参数
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
remove_locator_handler
Added in: v1.44移除由 page.add_locator_handler() 为特定定位器添加的所有定位器处理程序。
🌐 Removes all locator handlers added by page.add_locator_handler() for a specific locator.
用法
page.remove_locator_handler(locator)
参数
-
传递给 page.add_locator_handler() 的定位器。
返回
request_gc
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.
- Sync
- Async
# 1. In your page, save a WeakRef for the "suspect".
page.evaluate("globalThis.suspectWeakRef = new WeakRef(suspect)")
# 2. Request garbage collection.
page.request_gc()
# 3. Check that weak ref does not deref to the original object.
assert page.evaluate("!globalThis.suspectWeakRef.deref()")
# 1. In your page, save a WeakRef for the "suspect".
await page.evaluate("globalThis.suspectWeakRef = new WeakRef(suspect)")
# 2. Request garbage collection.
await page.request_gc()
# 3. Check that weak ref does not deref to the original object.
assert await page.evaluate("!globalThis.suspectWeakRef.deref()")
用法
page.request_gc()
返回
requests
Added in: v1.56返回此页面最多(当前)100条最近的网络请求。有关更多详情,请参见 page.on("request")。
🌐 Returns up to (currently) 100 last network request from this page. See page.on("request") 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.on("request") 请求报告的请求不会被收集,因此在使用 page.requests() 提高内存使用效率与通过 page.on("request") 报告的可用信息量之间存在权衡。
🌐 Note that requests reported through the page.on("request") 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.on("request").
用法
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 拦截的请求。请参见 this 问题。我们建议在使用请求拦截时禁用 Service Worker,通过将 service_workers 设置为 'block' 来实现。
page.route() 不会拦截弹出页面的第一个请求。请改用 browser_context.route() 。
用法
中止所有图片请求的简单处理程序的示例:
🌐 An example of a naive handler that aborts all image requests:
- Sync
- Async
page = browser.new_page()
page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()
page = await browser.new_page()
await page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
await page.goto("https://example.com")
await browser.close()
或使用正则表达式模式的相同片段:
🌐 or the same snippet using a regex pattern instead:
- Sync
- Async
page = browser.new_page()
page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
page.goto("https://example.com")
browser.close()
page = await browser.new_page()
await page.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
await page.goto("https://example.com")
await 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:
- Sync
- Async
def handle_route(route: Route):
if ("my-string" in route.request.post_data):
route.fulfill(body="mocked-data")
else:
route.continue_()
page.route("/api/**", handle_route)
async def handle_route(route: Route):
if ("my-string" in route.request.post_data):
await route.fulfill(body="mocked-data")
else:
await route.continue_()
await page.route("/api/**", handle_route)
当请求同时匹配两个处理程序时,页面路由优先于浏览器上下文路由(通过 browser_context.route() 设置)。
🌐 Page routes take precedence over browser context routes (set up with browser_context.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.
参数
-
urlstr | Pattern | Callable[URL]:bool#一个通配符模式、正则表达式模式或谓词,用于在路由期间接收要匹配的 URL。如果在上下文选项中设置了 base_url,并且提供的 URL 是一个不以
*开头的字符串,则会使用new URL()构造函数进行解析。 -
handlerCallable[Route, Request]:Promise[Any] | Any#处理程序函数来路由请求。
-
timesint (optional) Added in: v1.15#一个路由应该使用的频率。默认情况下,它将每次都被使用。
返回
route_from_har
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 文件中被 Service Worker 拦截的请求。请参见 此处 的问题。我们建议在使用请求拦截时禁用 Service Worker,通过将 service_workers 设置为 '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 service_workers to 'block'.
用法
page.route_from_har(har)
page.route_from_har(har, **kwargs)
参数
-
harUnion[str, pathlib.Path]#指向包含预录网络数据的 HAR 文件的路径。如果
path是相对路径,则相对于当前工作目录进行解析。 -
not_found"abort" | "fallback" (optional)#- 如果设置为“中止”,任何在 HAR 文件中未找到的请求都将被中止。
- 如果设置为“fallback”,缺失的请求将发送到网络。
默认为中止。
-
如果指定,会使用实际的网络信息更新给定的 HAR,而不是从文件提供。当调用 browser_context.close() 时,文件会写入磁盘。
-
update_content"embed" | "attach" (optional) Added in: v1.32#可选设置,用于控制资源内容管理。如果指定
attach,资源将作为单独的文件或 ZIP 压缩包中的条目进行保存。如果指定embed,内容将存储在 HAR 文件中。 -
update_mode"full" | "minimal" (optional) Added in: v1.32#当设置为
minimal时,仅记录从 HAR 路由所需的信息。这会省略在从 HAR 回放时不使用的大小、时间、页面、Cookies、安全性以及其他类型的 HAR 信息。默认值为minimal。 -
用于匹配请求 URL 的通配符模式、正则表达式或谓词。只有 URL 匹配该模式的请求才会从 HAR 文件中提供服务。如果未指定,则所有请求都将从 HAR 文件中提供服务。
返回
route_web_socket
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.
- Sync
- Async
def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "request":
ws.send("response")
def handler(ws: WebSocketRoute):
ws.on_message(lambda message: message_handler(ws, message))
page.route_web_socket("/ws", handler)
def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
if message == "request":
ws.send("response")
def handler(ws: WebSocketRoute):
ws.on_message(lambda message: message_handler(ws, message))
await page.route_web_socket("/ws", handler)
参数
-
urlstr | Pattern | Callable[URL]:bool#只有 URL 符合此模式的 WebSocket 才会被路由。字符串模式可以相对于 base_url 上下文选项。
-
handlerCallable[WebSocketRoute]:Promise[Any] | Any#路由 WebSocket 的处理程序函数。
返回
screenshot
Added before v1.9返回带有捕获的屏幕截图的缓冲区。
🌐 Returns the buffer with the captured screenshot.
用法
page.screenshot()
page.screenshot(**kwargs)
参数
-
animations"disabled" | "allow" (optional)#当设置为
"disabled"时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:- 有限动画会被快进至完成,因此它们会触发
transitionend事件。 - 无限动画被取消到初始状态,然后在屏幕截图后播放。
默认值为
"allow",不会改变动画。 - 有限动画会被快进至完成,因此它们会触发
-
caret"hide" | "initial" (optional)#当设置为
"hide"时,截图将隐藏文本光标。当设置为"initial"时,文本光标的行为不会改变。默认值为"hide"。 -
指定对结果图片进行裁剪的对象。
-
当为真时,会截取整个可滚动页面的截图,而不是当前可见的视口。默认值为
false。 -
maskList[Locator] (optional)#指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉色方框
#FF00FF覆盖(可通过 mask_color 自定义),完全覆盖其边界框。遮罩也会应用到不可见元素,参见 仅匹配可见元素 可禁用该功能。 -
mask_colorstr (optional) Added in: v1.35#指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色
#FF00FF。 -
omit_backgroundbool (optional)#隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于
jpeg图片。默认值为false。 -
pathUnion[str, pathlib.Path] (optional)#保存图片的文件路径。截图类型将根据文件扩展名来推断。如果path是相对路径,则相对于当前工作目录进行解析。如果未提供路径,则图片不会保存到磁盘上。
-
图片质量,范围为0-100。不适用于
png图片。 -
scale"css" | "device" (optional)#当设置为
"css"时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用"device"选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。默认为
"device"。 -
stylestr (optional) Added in: v1.41#在截图时要应用的样式表文本。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。此样式表可以穿透 Shadow DOM 并应用于内部框架。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
type"png" | "jpeg" (optional)#指定截图类型,默认为
png。
返回
set_content
Added before v1.9该方法在内部调用了 document.write(),继承了其所有特定的特性和行为。
🌐 This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
用法
page.set_content(html)
page.set_content(html, **kwargs)
参数
-
要分配给页面的 HTML 标记。
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
set_default_navigation_timeout
Added before v1.9此设置将更改以下方法和相关快捷方式的默认最大导航时间:
🌐 This setting will change the default maximum navigation time for the following methods and related shortcuts:
- page.go_back()
- page.go_forward()
- page.goto()
- page.reload()
- page.set_content()
- page.expect_navigation()
- page.wait_for_url()
用法
page.set_default_navigation_timeout(timeout)
参数
set_default_timeout
Added before v1.9此设置将更改所有接受 timeout 选项的方法的默认最大时间。
🌐 This setting will change the default maximum time for all the methods accepting timeout option.
用法
page.set_default_timeout(timeout)
参数
set_extra_http_headers
Added before v1.9额外的 HTTP 标头将随页面发起的每个请求一起发送。
🌐 The extra HTTP headers will be sent with every request the page initiates.
page.set_extra_http_headers() 不保证发送请求中头部的顺序。
用法
page.set_extra_http_headers(headers)
参数
返回
set_viewport_size
Added before v1.9在单个浏览器中,如果有多个页面,每个页面可以有自己的视口大小。然而,browser.new_context() 允许一次性为上下文中的所有页面设置视口大小(以及更多设置)。
🌐 In the case of multiple pages in a single browser, each page can have its own viewport size. However, browser.new_context() allows to set viewport size (and more) for all pages in the context at once.
page.set_viewport_size() 将调整页面大小。许多网站并不预计手机会改变尺寸,因此你应该在导航到页面之前设置视口大小。page.set_viewport_size() 还会重置 screen 的大小,如果你需要更好地控制这些属性,请使用带有 screen 和 viewport 参数的 browser.new_context()。
用法
- Sync
- Async
page = browser.new_page()
page.set_viewport_size({"width": 640, "height": 480})
page.goto("https://example.com")
page = await browser.new_page()
await page.set_viewport_size({"width": 640, "height": 480})
await page.goto("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, **kwargs)
参数
-
urlstr | Pattern | Callable[URL]:bool#在路由期间接收 URL 进行匹配的 glob 模式、正则表达式模式或谓词。
-
handlerCallable[Route, Request]:Promise[Any] | Any (optional)#用于路由请求的可选处理程序函数。
返回
unroute_all
Added in: v1.41移除使用 page.route() 和 page.route_from_har() 创建的所有路由。
🌐 Removes all routes created with page.route() and page.route_from_har().
用法
page.unroute_all()
page.unroute_all(**kwargs)
参数
-
behavior"wait" | "ignoreErrors" | "default" (optional)#指定是否等待已经运行的处理程序以及如果它们抛出错误该怎么办:
'default'- 不要等待当前处理程序调用(如果有)完成,如果未路由的处理程序抛出异常,可能会导致未处理的错误'wait'- 等待当前处理程序的调用(如果有)完成'ignoreErrors'- 不要等待当前处理程序的调用(如果有)完成,在取消路由后,处理程序抛出的所有错误都会被静默捕获
返回
wait_for_event
Added before v1.9在大多数情况下,你应该使用 page.expect_event()。
🌐 In most cases, you should use page.expect_event().
等待给定的 event 触发。如果提供了谓词,它会将事件的值传入 predicate 函数,并等待 predicate(event) 返回一个真值。如果页面在 event 触发之前关闭,将会抛出错误。
🌐 Waits for given event to fire. If predicate is provided, it passes event's value into the predicate function and waits for predicate(event) to return a truthy value. Will throw an error if the page is closed before the event is fired.
用法
page.wait_for_event(event)
page.wait_for_event(event, **kwargs)
参数
-
事件名称,通常传递到
*.on(event)的那个相同名称。 -
predicateCallable (optional)#接收事件数据并在等待解决时解析为真值。
-
等待的最长时间(以毫秒为单位)。默认为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 来更改默认值。
返回
wait_for_function
Added before v1.9当 expression 返回真值时返回。它解析为该真值的 JSHandle。
🌐 Returns when the expression returns a truthy value. It resolves to a JSHandle of the truthy value.
用法
page.wait_for_function() 可用于观察视口大小的变化:
🌐 The page.wait_for_function() can be used to observe viewport size change:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch()
page = browser.new_page()
page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);")
page.wait_for_function("() => window.x > 0")
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
webkit = playwright.webkit
browser = await webkit.launch()
page = await browser.new_page()
await page.evaluate("window.x = 0; setTimeout(() => { window.x = 100 }, 1000);")
await page.wait_for_function("() => window.x > 0")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
要向 page.wait_for_function() 函数的谓词传递参数:
🌐 To pass an argument to the predicate of page.wait_for_function() function:
- Sync
- Async
selector = ".foo"
page.wait_for_function("selector => !!document.querySelector(selector)", selector)
selector = ".foo"
await page.wait_for_function("selector => !!document.querySelector(selector)", selector)
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
-
pollingfloat | "raf" (optional)#如果 轮询 是
'raf',那么 表达式 会在requestAnimationFrame回调中持续执行。如果 轮询 是一个数字,则将其视为以毫秒为单位的间隔,在该间隔下函数将被执行。默认值为raf。 -
等待的最长时间,以毫秒为单位。默认值为
30000(30 秒)。传入0可禁用超时。可以使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法更改默认值。
返回
wait_for_load_state
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.
用法
- Sync
- Async
page.get_by_role("button").click() # click triggers navigation.
page.wait_for_load_state() # the promise resolves after "load" event.
await page.get_by_role("button").click() # click triggers navigation.
await page.wait_for_load_state() # the promise resolves after "load" event.
- Sync
- Async
with page.expect_popup() as page_info:
page.get_by_role("button").click() # click triggers a popup.
popup = page_info.value
# Wait for the "DOMContentLoaded" event.
popup.wait_for_load_state("domcontentloaded")
print(popup.title()) # popup is ready to use.
async with page.expect_popup() as page_info:
await page.get_by_role("button").click() # click triggers a popup.
popup = await page_info.value
# Wait for the "DOMContentLoaded" event.
await popup.wait_for_load_state("domcontentloaded")
print(await popup.title()) # popup is ready to use.
参数
-
state"load" | "domcontentloaded" | "networkidle" (optional)#可选的加载状态,默认值为
load。如果在加载当前文档时该状态已达到,方法会立即完成。可以是以下之一:'load'- 等待load事件触发。'domcontentloaded'- 等待DOMContentLoaded事件触发。'networkidle'- 不建议 等待直到至少500毫秒内没有网络连接。不要使用此方法进行测试,而应依赖网络断言来评估准备情况。
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
wait_for_url
Added in: v1.11等待主框架导航到给定的 URL。
🌐 Waits for the main frame to navigate to the given URL.
用法
- Sync
- Async
page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
page.wait_for_url("**/target.html")
await page.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
await page.wait_for_url("**/target.html")
参数
-
urlstr | Pattern | Callable[URL]:bool#一个通配符模式、正则表达式模式或接收 URL 的谓词,用于在等待导航时进行匹配。请注意,如果参数是没有通配符字符的字符串,该方法将等待导航到与该字符串完全相同的 URL。
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
属性
🌐 Properties
clock
Added in: v1.45Playwright 能够模拟时钟和时间的流逝。
🌐 Playwright has ability to mock clock and passage of time.
用法
page.clock
类型
context
Added before v1.9获取页面所属的浏览器上下文。
🌐 Get the browser context that the page belongs to.
用法
page.context
返回
frames
Added before v1.9附加到页面的所有框架的数组。
🌐 An array of all frames attached to the page.
用法
page.frames
返回
is_closed
Added before v1.9表示该页面已关闭。
🌐 Indicates that the page has been closed.
用法
page.is_closed()
返回
keyboard
Added before v1.9用法
page.keyboard
类型
main_frame
Added before v1.9页面的主框架。页面保证有一个在导航期间持续存在的主框架。
🌐 The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
用法
page.main_frame
返回
mouse
Added before v1.9用法
page.mouse
类型
request
Added in: v1.16与此页面相关的 API 测试助手。此方法返回与页面上下文中的 browser_context.request 相同的实例。有关更多详情,请参见 browser_context.request。
🌐 API testing helper associated with this page. This method returns the same instance as browser_context.request on the page's context. See browser_context.request for more details.
用法
page.request
类型
touchscreen
Added before v1.9用法
page.touchscreen
类型
url
Added before v1.9用法
page.url
返回
video
Added before v1.9与此页面关联的视频对象。
🌐 Video object associated with this page.
用法
page.video
返回
viewport_size
Added before v1.9用法
page.viewport_size
返回
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
返回
事件
🌐 Events
on("close")
Added before v1.9页面关闭时触发。
🌐 Emitted when the page closes.
用法
page.on("close", handler)
事件数据
on("console")
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.
用法
- Sync
- Async
def print_args(msg):
for arg in msg.args:
print(arg.json_value())
page.on("console", print_args)
page.evaluate("console.log('hello', 5, { foo: 'bar' })")
async def print_args(msg):
values = []
for arg in msg.args:
values.append(await arg.json_value())
print(values)
page.on("console", print_args)
await page.evaluate("console.log('hello', 5, { foo: 'bar' })")
事件数据
on("crash")
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:
- Sync
- Async
try:
# crash might happen during a click.
page.click("button")
# or while waiting for an event.
page.wait_for_event("popup")
except Error as e:
pass
# when the page crashes, exception message contains "crash".
try:
# crash might happen during a click.
await page.click("button")
# or while waiting for an event.
await page.wait_for_event("popup")
except Error as e:
pass
# when the page crashes, exception message contains "crash".
用法
page.on("crash", handler)
事件数据
on("dialog")
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.on("dialog", lambda dialog: dialog.accept())
当没有[page.on(“dialog”)](/api/class-page.mdx#page-event-dialog)或[browser_context.on(“dialog”)](/api/class-browsercontext.mdx#browser-context-event-dialog)监听者时,所有对话都会自动被关闭。
事件数据
on("domcontentloaded")
Added in: v1.9当 JavaScript DOMContentLoaded 事件被分发时触发。
🌐 Emitted when the JavaScript DOMContentLoaded event is dispatched.
用法
page.on("domcontentloaded", handler)
事件数据
on("download")
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.on("download", handler)
事件数据
on("filechooser")
Added in: v1.9当文件选择器应该出现时,比如点击 <input type=file> 后,会发出。Playwright可以通过设置输入文件 file_chooser.set_files() 来回应,之后可以上传。
🌐 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 file_chooser.set_files() that can be uploaded after that.
page.on("filechooser", lambda file_chooser: file_chooser.set_files("/tmp/myfile.pdf"))
用法
page.on("filechooser", handler)
事件数据
on("frameattached")
Added in: v1.9当附加框架时触发。
🌐 Emitted when a frame is attached.
用法
page.on("frameattached", handler)
事件数据
on("framedetached")
Added in: v1.9当框架分离时触发。
🌐 Emitted when a frame is detached.
用法
page.on("framedetached", handler)
事件数据
on("framenavigated")
Added in: v1.9当框架导航到新的 url 时触发。
🌐 Emitted when a frame is navigated to a new url.
用法
page.on("framenavigated", handler)
事件数据
on("load")
Added before v1.9当 JavaScript load 事件被分发时触发。
🌐 Emitted when the JavaScript load event is dispatched.
用法
page.on("load", handler)
事件数据
on("pageerror")
Added in: v1.9当页面内发生未捕获的异常时触发。
🌐 Emitted when an uncaught exception happens within the page.
- Sync
- Async
# Log all uncaught errors to the terminal
page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}"))
# Navigate to a page with an exception.
page.goto("data:text/html,<script>throw new Error('test')</script>")
# Log all uncaught errors to the terminal
page.on("pageerror", lambda exc: print(f"uncaught exception: {exc}"))
# Navigate to a page with an exception.
await page.goto("data:text/html,<script>throw new Error('test')</script>")
用法
page.on("pageerror", handler)
事件数据
on("popup")
Added before v1.9当页面打开新标签页或窗口时触发。此事件会与 browser_context.on("page") 一起触发,但仅针对与此页面相关的弹出窗口。
🌐 Emitted when the page opens a new tab or window. This event is emitted in addition to the browser_context.on("page"), but only for popups relevant to this page.
页面最早可用的时刻是在它导航到初始 URL 时。例如,当使用 window.open('http://example.com') 打开弹出窗口时,当网络请求到 "http://example.com" 完成并且其响应开始在弹出窗口中加载时,将触发此事件。如果你想要路由/监听此网络请求,请使用 browser_context.route() 和 browser_context.on("request"),而不是 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 browser_context.route() and browser_context.on("request") respectively instead of similar methods on the Page.
- Sync
- Async
with page.expect_event("popup") as page_info:
page.get_by_text("open the popup").click()
popup = page_info.value
print(popup.evaluate("location.href"))
async with page.expect_event("popup") as page_info:
await page.get_by_text("open the popup").click()
popup = await page_info.value
print(await popup.evaluate("location.href"))
使用 page.wait_for_load_state() 等待页面达到特定状态(在大多数情况下你通常不需要它)。
🌐 Use page.wait_for_load_state() to wait until the page gets to a particular state (you should not need it in most cases). :::
用法
page.on("popup", handler)
事件数据
on("request")
Added before v1.9当页面发出请求时触发。[request] 对象是只读的。要拦截和修改请求,请参见 [page.route()](/api/class-page.mdx#page-route) 或 [browser_context.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 browser_context.route().
用法
page.on("request", handler)
事件数据
on("requestfailed")
Added in: v1.9当请求失败时触发,例如超时。
🌐 Emitted when a request fails, for example by timing out.
page.on("requestfailed", lambda request: print(request.url + " " + request.failure.error_text))
HTTP 错误响应,例如 404 或 503,从 HTTP 的角度来看仍然是成功的响应,因此请求将通过 page.on("requestfinished") 事件完成,而不是通过 page.on("requestfailed") 事件完成。只有在客户端无法从服务器获取 HTTP 响应时,请求才会被视为失败,例如由于网络错误 net::ERR_FAILED。
用法
page.on("requestfailed", handler)
事件数据
on("requestfinished")
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.on("requestfinished", handler)
事件数据
on("response")
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.on("response", handler)
事件数据
on("websocket")
Added in: v1.9当发送 WebSocket 请求时触发。
🌐 Emitted when WebSocket request is sent.
用法
page.on("websocket", handler)
事件数据
on("worker")
Added before v1.9当页面生成专用的 WebWorker 时触发。
🌐 Emitted when a dedicated WebWorker is spawned by the page.
用法
page.on("worker", 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 中。
- 确保匹配的元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
- 等待匹配元素的 可操作性 检查,除非设置了 强制 选项。如果元素在检查过程中被分离,整个操作将重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 点击元素的中心。
- 确保该元素现在已被选中。如果没有,该方法会抛出异常。
当所有步骤在指定的 timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
page.check(selector)
page.check(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
positionDict (optional) Added in: v1.11#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (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 中。
- 等待匹配元素的 可操作性 检查,除非设置了 强制 选项。如果元素在检查过程中被分离,整个操作将重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 点击元素中心,或指定的 position 位置。
- 等待已启动的导航要么成功,要么失败,除非设置了 no_wait_after 选项。
当所有步骤在指定的 timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
page.click(selector)
page.click(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
button"left" | "right" | "middle" (optional)#默认为
left。 -
默认为 1。请参阅 UIEvent.detail。
-
mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
modifiersList["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
no_wait_afterbool (optional)#已弃用此选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (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 中。
- 等待匹配元素的可操作性检查,除非设置了强制选项。如果在检查期间元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 在元素中心或指定的 position 双击。
当所有步骤在指定的超时内未完成时,该方法会抛出[超时错误]。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
page.dblclick() 触发两个 click 事件和一个 dblclick 事件。
用法
page.dblclick(selector)
page.dblclick(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
button"left" | "right" | "middle" (optional)#默认为
left。 -
mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
modifiersList["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
返回
dispatch_event
Added before v1.9请改为使用基于定位器的 locator.dispatch_event()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.dispatch_event() 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().
用法
- Sync
- Async
page.dispatch_event("button#submit", "click")
await page.dispatch_event("button#submit", "click")
在底层,它会根据给定的type创建一个事件实例,使用event_init属性初始化该事件,并在元素上分发。事件是composed、cancelable,默认情况下会冒泡。
🌐 Under the hood, it creates an instance of an event based on the given type, initializes it with event_init properties and dispatches it on the element. Events are composed, cancelable and bubble by default.
由于 event_init 是特定于事件的,请查阅事件文档以获取初始属性列表:
🌐 Since event_init 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:
- Sync
- Async
# note you can only create data_transfer in chromium and firefox
data_transfer = page.evaluate_handle("new DataTransfer()")
page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })
# note you can only create data_transfer in chromium and firefox
data_transfer = await page.evaluate_handle("new DataTransfer()")
await page.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
DOM 事件类型:
"click"、"dragstart"等 -
event_initEvaluationArgument (optional)#可选的特定于事件的初始化属性。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
eval_on_selector
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.eval_on_selector() 会等待该 promise 解决并返回其值。
🌐 If expression returns a Promise, then page.eval_on_selector() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
search_value = page.eval_on_selector("#search", "el => el.value")
preload_href = page.eval_on_selector("link[rel=preload]", "el => el.href")
html = page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello")
search_value = await page.eval_on_selector("#search", "el => el.value")
preload_href = await page.eval_on_selector("link[rel=preload]", "el => el.href")
html = await page.eval_on_selector(".main-container", "(e, suffix) => e.outer_html + suffix", "hello")
参数
-
要查询的选择器。
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
返回
eval_on_selector_all
Added in: v1.9在大多数情况下,locator.evaluate_all()、其他 Locator 辅助方法以及以网页为先的断言效果更好。
🌐 In most cases, locator.evaluate_all(), 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.eval_on_selector_all() 会等待该 Promise 解决并返回其值。
🌐 If expression returns a Promise, then page.eval_on_selector_all() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
div_counts = page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
div_counts = await page.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
参数
-
要查询的选择器。
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
expect_navigation
Added before v1.9这种方法本质上存在竞争问题,请改用 page.wait_for_url()。
🌐 This method is inherently racy, please use page.wait_for_url() 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:
- Sync
- Async
with page.expect_navigation():
# This action triggers the navigation after a timeout.
page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished
async with page.expect_navigation():
# This action triggers the navigation after a timeout.
await page.get_by_text("Navigate after timeout").click()
# Resolves after navigation has finished
使用 History API 更改 URL 被视为一次导航。
🌐 Usage of the History API to change the URL is considered a navigation.
参数
-
最大操作时间(以毫秒为单位),默认为 30 秒,传入
0可禁用超时。默认值可以通过使用 browser_context.set_default_navigation_timeout()、browser_context.set_default_timeout()、page.set_default_navigation_timeout() 或 page.set_default_timeout() 方法进行更改。 -
urlstr | Pattern | Callable[URL]:bool (optional)#一个通配符模式、正则表达式模式或接收 URL 的谓词,用于在等待导航时进行匹配。请注意,如果参数是没有通配符字符的字符串,该方法将等待导航到与该字符串完全相同的 URL。
-
wait_until"load" | "domcontentloaded" | "networkidle" | "commit" (optional)#何时认为操作成功,默认为
load。事件可以是以下之一:'domcontentloaded'- 当触发DOMContentLoaded事件时,视操作为完成。'load'- 当触发load事件时,视操作为完成。'networkidle'- 不推荐 在没有网络连接至少500毫秒时就认为操作已完成。不要使用此方法进行测试,应依赖网页断言来评估就绪状态。'commit'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
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.press_sequentially()。
🌐 To send fine-grained keyboard events, use locator.press_sequentially().
用法
page.fill(selector, value)
page.fill(selector, value, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
为
<input>、<textarea>或[contenteditable]元素填写的值。 -
forcebool (optional) Added in: v1.13#是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
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, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
get_attribute
Added before v1.9请改用基于定位器的 locator.get_attribute()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.get_attribute() instead. Read more about locators.
返回元素属性值。
🌐 Returns element attribute value.
用法
page.get_attribute(selector, name)
page.get_attribute(selector, name, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
要获取其值的属性名称。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
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 中。
- 等待对匹配元素的 可操作性 检查,除非已设置 强制 选项。如果在检查过程中元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 将鼠标悬停在元素中心,或指定的 position 上。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
page.hover(selector)
page.hover(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
false。 -
modifiersList["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
no_wait_afterbool (optional) Added in: v1.28#已弃用此选项无效。
此选项无效。
-
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
返回
inner_html
Added before v1.9请改用基于定位器的 locator.inner_html()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.inner_html() instead. Read more about locators.
返回 element.innerHTML。
🌐 Returns element.innerHTML.
用法
page.inner_html(selector)
page.inner_html(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
inner_text
Added before v1.9请改为使用基于定位器的 locator.inner_text()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.inner_text() instead. Read more about locators.
返回 element.innerText。
🌐 Returns element.innerText.
用法
page.inner_text(selector)
page.inner_text(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
input_value
Added in: v1.13请改用基于定位器的 locator.input_value()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.input_value() 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.input_value(selector)
page.input_value(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
is_checked
Added before v1.9请改为使用基于定位器的 locator.is_checked()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.is_checked() instead. Read more about locators.
返回元素是否被选中。如果元素不是复选框或单选按钮,将抛出异常。
🌐 Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
用法
page.is_checked(selector)
page.is_checked(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
is_disabled
Added before v1.9请改为使用基于定位器的 locator.is_disabled()。阅读更多关于 定位器 的信息。
🌐 Use locator-based locator.is_disabled() instead. Read more about locators.
返回该元素是否被禁用,与enabled相反。
🌐 Returns whether the element is disabled, the opposite of enabled.
用法
page.is_disabled(selector)
page.is_disabled(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
is_editable
Added before v1.9请改用基于定位器的 locator.is_editable()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.is_editable() instead. Read more about locators.
返回元素是否可编辑。
🌐 Returns whether the element is editable.
用法
page.is_editable(selector)
page.is_editable(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
is_enabled
Added before v1.9请改用基于定位器的 locator.is_enabled()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.is_enabled() instead. Read more about locators.
返回元素是否已启用。
🌐 Returns whether the element is enabled.
用法
page.is_enabled(selector)
page.is_enabled(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
is_hidden
Added before v1.9请改为使用基于定位器的 locator.is_hidden()。阅读更多关于 定位器 的信息。
🌐 Use locator-based locator.is_hidden() 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.is_hidden(selector)
page.is_hidden(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。page.is_hidden() 不会等待元素隐藏,会立即返回。
返回
is_visible
Added before v1.9请改为使用基于定位器的 locator.is_visible()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.is_visible() instead. Read more about locators.
🌐 Returns whether the element is visible. selector that does not match any elements is considered not visible.
用法
page.is_visible(selector)
page.is_visible(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。page.is_visible() 不会等待元素变为可见,而是立即返回。
返回
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.
用法
- Sync
- Async
page = browser.new_page()
page.goto("https://keycode.info")
page.press("body", "A")
page.screenshot(path="a.png")
page.press("body", "ArrowLeft")
page.screenshot(path="arrow_left.png")
page.press("body", "Shift+O")
page.screenshot(path="o.png")
browser.close()
page = await browser.new_page()
await page.goto("https://keycode.info")
await page.press("body", "A")
await page.screenshot(path="a.png")
await page.press("body", "ArrowLeft")
await page.screenshot(path="arrow_left.png")
await page.press("body", "Shift+O")
await page.screenshot(path="o.png")
await browser.close()
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
输入按键名称或生成字符名称,如“ArrowLeft”或“a”。
-
keydown和keyup之间的等待时间,以毫秒为单位。默认值为 0。 -
no_wait_afterbool (optional)#已弃用此选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
query_selector
Added in: v1.9请改用基于定位器的 page.locator()。了解更多关于 定位器 的信息。
🌐 Use locator-based page.locator() instead. Read more about locators.
该方法会在页面中查找与指定选择器匹配的元素。如果没有元素匹配该选择器,返回值将解析为 null。要在页面上等待某个元素,请使用 locator.wait_for()。
🌐 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.wait_for().
用法
page.query_selector(selector)
page.query_selector(selector, **kwargs)
参数
-
要查询的选择器。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
返回
query_selector_all
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.query_selector_all(selector)
参数
返回
select_option
Added before v1.9请改为使用基于定位器的 locator.select_option()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.select_option() 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.
用法
- Sync
- Async
# Single selection matching the value or label
page.select_option("select#colors", "blue")
# single selection matching both the label
page.select_option("select#colors", label="blue")
# multiple selection
page.select_option("select#colors", value=["red", "green", "blue"])
# Single selection matching the value or label
await page.select_option("select#colors", "blue")
# single selection matching the label
await page.select_option("select#colors", label="blue")
# multiple selection
await page.select_option("select#colors", value=["red", "green", "blue"])
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
forcebool (optional) Added in: v1.13#是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
elementElementHandle | List[ElementHandle] (optional)#要选择的选项元素。可选。
-
indexint | List[int] (optional)#按索引选择的选项。可选。
-
valuestr | List[str] (optional)#按值选择的选项。如果
<select>拥有multiple属性,则选择所有给定的选项,否则只选择第一个匹配传入选项的选项。可选。 -
labelstr | List[str] (optional)#按标签选择的选项。如果
<select>拥有multiple属性,则选择所有给定的选项,否则只选择第一个匹配传入选项之一的选项。可选。
返回
set_checked
Added in: v1.15请改为使用基于定位器的 locator.set_checked()。阅读更多关于 定位器 的信息。
🌐 Use locator-based locator.set_checked() instead. Read more about locators.
此方法通过执行以下步骤来勾选或取消勾选与 selector 匹配的元素:
🌐 This method checks or unchecks an element matching selector by performing the following steps:
- 查找与 selector 匹配的元素。如果没有,等待直到有匹配的元素被添加到 DOM 中。
- 确保匹配的元素是复选框或单选按钮。如果不是,该方法将抛出异常。
- 如果元素已经具有正确的检查状态,则此方法立即返回。
- 等待匹配元素的可操作性检查,除非设置了强制选项。如果在检查期间元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 点击元素的中心。
- 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。
当所有步骤合并未在指定的[超时](/api/class-page.mdx#page-set-checked-option-timeout)内完成时,该方法会抛出[超时错误]。通过零超时则禁用。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
page.set_checked(selector, checked)
page.set_checked(selector, checked, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否选中或取消选中复选框。
-
是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
返回
set_input_files
Added before v1.9改用基于定位器的[locator.set_input_files()](/api/class-locator.mdx#locator-set-input-files)。阅读更多关于[定位器](../locators.mdx)的信息。
🌐 Use locator-based locator.set_input_files() 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.set_input_files(selector, files)
page.set_input_files(selector, files, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
filesUnion[str, pathlib.Path] | List[Union[str, pathlib.Path]] | Dict | List[Dict]# -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
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 中。
- 等待匹配元素的 可操作性 检查,除非设置了 强制 选项。如果元素在检查过程中被分离,整个操作将重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.touchscreen 点击元素的中心,或指定的 位置。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
page.tap() 方法将在浏览器上下文的 has_touch 选项为 false 时抛出异常。:::
用法
page.tap(selector)
page.tap(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
false。 -
modifiersList["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (optional) Added in: v1.11#设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
返回
text_content
Added before v1.9请改为使用基于定位器的 locator.text_content()。阅读更多关于 定位器 的内容。
🌐 Use locator-based locator.text_content() instead. Read more about locators.
返回 element.textContent。
🌐 Returns element.textContent.
用法
page.text_content(selector)
page.text_content(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
type
Added before v1.9在大多数情况下,你应该改用 locator.fill()。只有在页面上有特殊键盘处理时,才需要逐个按键,此时使用 locator.press_sequentially()。
🌐 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.press_sequentially().
对文本中的每个字符发送 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()。
🌐 To press a special key, like Control or ArrowDown, use keyboard.press().
用法
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
要输入到焦点元素中的文本。
-
按键之间的等待时间,以毫秒为单位。默认为 0。
-
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
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 中。
- 确保匹配的元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经未选中,该方法会立即返回。
- 等待对匹配元素的 可操作性 检查,除非已设置 强制 选项。如果在检查过程中元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 page.mouse 点击元素的中心。
- 确保该元素现在未被选中。如果不是,这种方法会抛出异常。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
page.uncheck(selector)
page.uncheck(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
false。 -
no_wait_afterbool (optional)#已弃用此选项无效。
此选项无效。
-
positionDict (optional) Added in: v1.11#相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。 -
trialbool (optional) Added in: v1.11#设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
返回
wait_for_selector
Added before v1.9改用断言网页元素可见性的 Web 断言,或基于定位器的 locator.wait_for()。阅读更多关于 定位器 的内容。
🌐 Use web assertions that assert visibility or a locator-based locator.wait_for() instead. Read more about locators.
当由选择器指定的元素满足 state 选项时返回。如果等待的是 hidden 或 detached,则返回 null。
🌐 Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.
等待 selector(/api/class-page.mdx#page-wait-for-selector-option-selector) 满足 [state](/api/class-page.mdx#page-wait-for-selector-option-state) 选项(要么从主导中出现/消失,要么变得可见/隐藏)。如果在调用方法[选择器](/api/class-page.mdx#page-wait-for-selector-option-selector)时已经满足该条件,方法将立即返回。如果选择器不满足[超时](/api/class-page.mdx#page-wait-for-selector-option-timeout)毫秒的条件,函数将抛出。
🌐 Wait for the selector to satisfy state 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 timeout milliseconds, the function will throw.
用法
此方法适用于多种导航:
🌐 This method works across navigations:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
for current_url in ["https://google.com", "https://bbc.com"]:
page.goto(current_url, wait_until="domcontentloaded")
element = page.wait_for_selector("img")
print("Loaded image: " + str(element.get_attribute("src")))
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
chromium = playwright.chromium
browser = await chromium.launch()
page = await browser.new_page()
for current_url in ["https://google.com", "https://bbc.com"]:
await page.goto(current_url, wait_until="domcontentloaded")
element = await page.wait_for_selector("img")
print("Loaded image: " + str(await element.get_attribute("src")))
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
参数
-
要查询的选择器。
-
state"attached" | "detached" | "visible" | "hidden" (optional)#默认值为
'visible'。可以是以下之一:'attached'- 等待元素出现在 DOM 中。'detached'- 等待元素不再出现在 DOM 中。'visible'- 等待元素有非空的边界框并且不含visibility:hidden。请注意,没有任何内容或含有display:none的元素会有空的边界框,并且不被认为是可见的。'hidden'- 等待元素被从 DOM 中移除,或其边界框为空,或为visibility:hidden。这与'visible'选项相反。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
wait_for_timeout
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.
用法
- Sync
- Async
# wait for 1 second
page.wait_for_timeout(1000)
# wait for 1 second
await page.wait_for_timeout(1000)
参数
返回