Frame
在任何时刻,页面都会通过 page.main_frame 和 frame.child_frames 方法暴露其当前的框架树。
🌐 At every point of time, page exposes its current frame tree via the page.main_frame and frame.child_frames methods.
Frame 对象的生命周期由三个事件控制,这些事件在页面对象上分发:
- page.on("frameattached") - 当框架被附加到页面时触发。一个框架只能被附加到页面一次。
- page.on("framenavigated") - 当框架提交导航到不同的 URL 时触发。
- page.on("framedetached") - 当框架从页面中分离时触发。一个框架只能从页面中分离一次。
转储框架树的示例:
🌐 An example of dumping frame tree:
- Sync
- Async
from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
firefox = playwright.firefox
browser = firefox.launch()
page = browser.new_page()
page.goto("https://www.theverge.com")
dump_frame_tree(page.main_frame, "")
browser.close()
def dump_frame_tree(frame, indent):
print(indent + frame.name + '@' + frame.url)
for child in frame.child_frames:
dump_frame_tree(child, indent + " ")
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
firefox = playwright.firefox
browser = await firefox.launch()
page = await browser.new_page()
await page.goto("https://www.theverge.com")
dump_frame_tree(page.main_frame, "")
await browser.close()
def dump_frame_tree(frame, indent):
print(indent + frame.name + '@' + frame.url)
for child in frame.child_frames:
dump_frame_tree(child, indent + " ")
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
方法
🌐 Methods
add_script_tag
Added before v1.9当脚本的 onload 触发或脚本内容注入框架时返回添加的标签。
🌐 Returns the added tag when the script's onload fires or when the script content was injected into frame.
在页面中添加一个包含所需 URL 或内容的 <script> 标签。
🌐 Adds a <script> tag into the page with the desired url or content.
用法
frame.add_script_tag()
frame.add_script_tag(**kwargs)
参数
-
要注入到框架中的原始 JavaScript 内容。
-
pathUnion[str, pathlib.Path] (optional)#要注入到框架中的 JavaScript 文件路径。如果
path是相对路径,则相对于当前工作目录解析。 -
脚本类型。使用 'module' 来加载 JavaScript ES6 模块。更多详情请参见 script。
-
要添加的脚本的 URL。
返回
add_style_tag
Added before v1.9当样式表的 onload 触发或 CSS 内容注入框架时返回添加的标签。
🌐 Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
在页面中添加一个带有所需 URL 的 <link rel="stylesheet"> 标签或一个带有内容的 <style type="text/css"> 标签。
🌐 Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content.
用法
frame.add_style_tag()
frame.add_style_tag(**kwargs)
参数
-
要注入到框架中的原始 CSS 内容。
-
pathUnion[str, pathlib.Path] (optional)#要注入到框架中的 CSS 文件路径。如果
path是相对路径,则相对于当前工作目录解析。 -
<link>标签的 URL。
返回
content
Added before v1.9获取框架的完整 HTML 内容,包括文档类型。
🌐 Gets the full HTML contents of the frame, including the doctype.
用法
frame.content()
返回
drag_and_drop
Added in: v1.13用法
frame.drag_and_drop(source, target)
frame.drag_and_drop(source, target, **kwargs)
参数
-
用于搜索要拖动的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
用于搜索要放置的元素的选择器。如果有多个元素符合该选择器,将使用第一个元素。
-
是否绕过 可操作性 检查。默认值为
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。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
返回
evaluate
Added before v1.9返回 expression 的返回值。
🌐 Returns the return value of expression.
如果传递给 frame.evaluate() 的函数返回一个 Promise,那么 frame.evaluate() 将会等待该 promise 被解析并返回它的值。
🌐 If the function passed to the frame.evaluate() returns a Promise, then frame.evaluate() would wait for the promise to resolve and return its value.
如果传递给 frame.evaluate() 的函数返回一个非 Serializable 值,那么 frame.evaluate() 将返回 undefined。Playwright 还支持传递一些 JSON 无法序列化的其他值:-0、NaN、Infinity、-Infinity。
🌐 If the function passed to the frame.evaluate() returns a non-Serializable value, then frame.evaluate() returns undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.
用法
- Sync
- Async
result = frame.evaluate("([x, y]) => Promise.resolve(x * y)", [7, 8])
print(result) # prints "56"
result = await frame.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(frame.evaluate("1 + 2")) # prints "3"
x = 10
print(frame.evaluate(f"1 + {x}")) # prints "11"
print(await frame.evaluate("1 + 2")) # prints "3"
x = 10
print(await frame.evaluate(f"1 + {x}")) # prints "11"
ElementHandle 实例可以作为参数传递给 frame.evaluate():
- Sync
- Async
body_handle = frame.evaluate("document.body")
html = frame.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
body_handle.dispose()
body_handle = await frame.evaluate("document.body")
html = await frame.evaluate("([body, suffix]) => body.innerHTML + suffix", [body_handle, "hello"])
await body_handle.dispose()
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
evaluate_handle
Added before v1.9将 expression 的返回值作为 JSHandle 返回。
🌐 Returns the return value of expression as a JSHandle.
frame.evaluate() 和 frame.evaluate_handle() 唯一的区别是 frame.evaluate_handle() 会返回 JSHandle。
🌐 The only difference between frame.evaluate() and frame.evaluate_handle() is that frame.evaluate_handle() returns JSHandle.
如果传递给 frame.evaluate_handle() 的函数返回一个 Promise,那么 frame.evaluate_handle() 会等待该 promise 解析完成并返回其值。
🌐 If the function, passed to the frame.evaluate_handle(), returns a Promise, then frame.evaluate_handle() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
a_window_handle = frame.evaluate_handle("Promise.resolve(window)")
a_window_handle # handle for the window object.
a_window_handle = await frame.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 实例可以作为参数传递给 frame.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。
返回
frame_element
Added before v1.9返回与此框架对应的 frame 或 iframe 元素句柄。
🌐 Returns the frame or iframe element handle which corresponds to this frame.
这是 element_handle.content_frame() 的逆操作。请注意,返回的句柄实际上属于父框架。
🌐 This is an inverse of element_handle.content_frame(). Note that returned handle actually belongs to the parent frame.
如果在 frameElement() 返回之前帧已被分离,则此方法会抛出错误。
🌐 This method throws an error if the frame has been detached before frameElement() returns.
用法
- Sync
- Async
frame_element = frame.frame_element()
content_frame = frame_element.content_frame()
assert frame == content_frame
frame_element = await frame.frame_element()
content_frame = await frame_element.content_frame()
assert frame == content_frame
返回
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 = frame.frame_locator("#my-iframe").get_by_text("Submit")
locator.click()
locator = frame.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。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。
返回
goto
Added before v1.9返回主要资源响应。如果有多次重定向,导航将以最后一次重定向的响应作为结果。
🌐 Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
如果出现以下情况,该方法将抛出错误:
🌐 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 文档。请参阅上游问题。
用法
frame.goto(url)
frame.goto(url, **kwargs)
参数
-
框架要导航到的 URL。URL 应包含协议,例如
https://。 -
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'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
is_enabled
Added before v1.9返回元素是否已启用。
🌐 Returns whether the element is enabled.
用法
frame.is_enabled(selector)
frame.is_enabled(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 browser_context.set_default_timeout() 或 page.set_default_timeout() 方法进行更改。
返回
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.
用法
frame.locator(selector)
frame.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>。
返回
set_content
Added before v1.9该方法在内部调用了 document.write(),继承了其所有特定的特性和行为。
🌐 This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
用法
frame.set_content(html)
frame.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'- 当收到网络响应并且文档开始加载时,认为操作已完成。
返回
title
Added before v1.9返回页面标题。
🌐 Returns the page title.
用法
frame.title()
返回
wait_for_function
Added before v1.9当 expression 返回真值时,返回该值。
🌐 Returns when the expression returns a truthy value, returns that value.
用法
frame.wait_for_function() 可用于观察视口大小的变化:
🌐 The frame.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.main_frame.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.main_frame.wait_for_function("() => window.x > 0")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
要向 frame.waitForFunction 函数的谓词传递一个参数:
🌐 To pass an argument to the predicate of frame.waitForFunction function:
- Sync
- Async
selector = ".foo"
frame.wait_for_function("selector => !!document.querySelector(selector)", selector)
selector = ".foo"
await frame.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等待达到所需的加载状态。
🌐 Waits for the required load state to be reached.
当帧达到所需的加载状态时(默认是 load)此方法会返回。调用此方法时,导航必须已经提交。如果当前文档已经达到所需的状态,将立即执行返回。
🌐 This returns when the frame 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
frame.click("button") # click triggers navigation.
frame.wait_for_load_state() # the promise resolves after "load" event.
await frame.click("button") # click triggers navigation.
await frame.wait_for_load_state() # the promise resolves after "load" event.
参数
-
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 frame to navigate to the given URL.
用法
- Sync
- Async
frame.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
frame.wait_for_url("**/target.html")
await frame.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
await frame.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
child_frames
Added before v1.9用法
frame.child_frames
返回
is_detached
Added before v1.9如果框架已被分离,则返回 true,否则返回 false。
🌐 Returns true if the frame has been detached, or false otherwise.
用法
frame.is_detached()
返回
name
Added before v1.9返回标签中指定的框架的名称属性。
🌐 Returns frame's name attribute as specified in the tag.
如果名称为空,则返回 id 属性。
🌐 If the name is empty, returns the id attribute instead.
该值在创建帧时计算一次,如果稍后更改属性,值不会更新。
🌐 This value is calculated once when the frame is created, and will not update if the attribute is changed later.
用法
frame.name
返回
page
Added before v1.9返回包含此框架的页面。
🌐 Returns the page containing this frame.
用法
frame.page
返回
parent_frame
Added before v1.9父框架(如果有)。分离的框架和主框架返回 null。
🌐 Parent frame, if any. Detached frames and main frames return null.
用法
frame.parent_frame
返回
url
Added before v1.9返回框架的 url。
🌐 Returns frame's url.
用法
frame.url
返回
已弃用
🌐 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 点击元素的中心。
- 确保该元素现在已被选中。如果没有,该方法会抛出异常。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
frame.check(selector)
frame.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 选项。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
frame.click(selector)
frame.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 双击。如果
dblclick()的第一次点击触发导航事件,此方法将抛出异常。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
frame.dblclick() 触发两个 click 事件和一个 dblclick 事件。
用法
frame.dblclick(selector)
frame.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
frame.dispatch_event("button#submit", "click")
await frame.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 = frame.evaluate_handle("new DataTransfer()")
frame.dispatch_event("#source", "dragstart", { "dataTransfer": data_transfer })
# note you can only create data_transfer in chromium and firefox
data_transfer = await frame.evaluate_handle("new DataTransfer()")
await frame.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 the actionability checks and therefore can lead to the flaky tests. Use locator.evaluate(), other Locator helper methods or web-first assertions instead.
返回 expression 的返回值。
🌐 Returns the return value of expression.
该方法在框架中查找与指定选择器匹配的元素,并将其作为第一个参数传递给 expression。如果没有元素匹配该选择器,该方法会抛出错误。
🌐 The method finds an element matching the specified selector within the frame and passes it as a first argument to expression. If no elements match the selector, the method throws an error.
如果 expression 返回一个 Promise,那么 frame.eval_on_selector() 会等待该 promise 解决并返回其值。
🌐 If expression returns a Promise, then frame.eval_on_selector() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
search_value = frame.eval_on_selector("#search", "el => el.value")
preload_href = frame.eval_on_selector("link[rel=preload]", "el => el.href")
html = frame.eval_on_selector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello")
search_value = await frame.eval_on_selector("#search", "el => el.value")
preload_href = await frame.eval_on_selector("link[rel=preload]", "el => el.href")
html = await frame.eval_on_selector(".main-container", "(e, suffix) => e.outerHTML + 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 的返回值。
🌐 Returns the return value of expression.
该方法会查找框架内所有匹配指定选择器的元素,并将匹配元素数组作为第一个参数传递给 expression。
🌐 The method finds all elements matching the specified selector within the frame and passes an array of matched elements as a first argument to expression.
如果 expression 返回一个 Promise,那么 frame.eval_on_selector_all() 会等待该 Promise 解决并返回其值。
🌐 If expression returns a Promise, then frame.eval_on_selector_all() would wait for the promise to resolve and return its value.
用法
- Sync
- Async
divs_counts = frame.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
divs_counts = await frame.eval_on_selector_all("div", "(divs, min) => divs.length >= min", 10)
参数
-
要查询的选择器。
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument (optional)#可选参数,传递给 expression。
返回
expect_navigation
Added before v1.9这种方法本质上存在竞争问题,请改用 frame.wait_for_url()。
🌐 This method is inherently racy, please use frame.wait_for_url() instead.
等待框架导航并返回主资源响应。如果有多个重定向,导航将以最后一次重定向的响应为准。如果导航到不同的锚点或由于使用 History API 导致的导航,导航将以 null 解决。
🌐 Waits for the 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.
用法
此方法会等待框架导航到新的 URL。当你运行的代码会间接导致框架导航时,它非常有用。请参考以下示例:
🌐 This method waits for the frame to navigate to a new URL. It is useful for when you run code which will indirectly cause the frame to navigate. Consider this example:
- Sync
- Async
with frame.expect_navigation():
frame.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
# Resolves after navigation has finished
async with frame.expect_navigation():
await frame.click("a.delayed-navigation") # clicking the link will indirectly cause a navigation
# 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().
用法
frame.fill(selector, value)
frame.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.
用法
frame.focus(selector)
frame.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.
用法
frame.get_attribute(selector, name)
frame.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.
用法
frame.hover(selector)
frame.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.
用法
frame.inner_html(selector)
frame.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.
用法
frame.inner_text(selector)
frame.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.
用法
frame.input_value(selector)
frame.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.
用法
frame.is_checked(selector)
frame.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.
用法
frame.is_disabled(selector)
frame.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.
用法
frame.is_editable(selector)
frame.is_editable(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.
用法
frame.is_hidden(selector)
frame.is_hidden(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。frame.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.
用法
frame.is_visible(selector)
frame.is_visible(selector, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
-
已弃用
该选项会被忽略。frame.is_visible() 不会等待元素变为可见,并会立即返回。
返回
press
Added before v1.9请改为使用基于定位器的 locator.press()。了解更多关于 定位器 的信息。
🌐 Use locator-based locator.press() instead. Read more about locators.
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.
用法
frame.press(selector, key)
frame.press(selector, key, **kwargs)
参数
-
用于搜索元素的选择器。如果有多个元素符合选择器,将使用第一个元素。
-
输入按键名称或生成字符名称,如“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请改用基于定位器的 frame.locator()。了解更多关于 定位器 的信息。
🌐 Use locator-based frame.locator() instead. Read more about locators.
返回指向框架元素的 ElementHandle。
🌐 Returns the ElementHandle pointing to the frame element.
不鼓励使用 ElementHandle,请改用 Locator 对象和以网页为先的断言。
🌐 The use of ElementHandle is discouraged, use Locator objects and web-first assertions instead.
该方法在框架内查找与指定选择器匹配的元素。如果没有元素匹配该选择器,则返回 null。
🌐 The method finds an element matching the specified selector within the frame. If no elements match the selector, returns null.
用法
frame.query_selector(selector)
frame.query_selector(selector, **kwargs)
参数
-
要查询的选择器。
-
strictbool (optional) Added in: v1.14#当值为 true 时,该调用要求选择器解析为单个元素。如果给定的选择器解析为多个元素,该调用将抛出异常。
返回
query_selector_all
Added in: v1.9请改用基于定位器的 frame.locator()。了解更多关于 定位器 的信息。
🌐 Use locator-based frame.locator() instead. Read more about locators.
返回指向框架元素的 ElementHandles。
🌐 Returns the ElementHandles pointing to the frame elements.
不推荐使用 ElementHandle,请改用 Locator 对象。
🌐 The use of ElementHandle is discouraged, use Locator objects instead.
该方法会在框架内查找所有匹配指定选择器的元素。如果没有元素匹配该选择器,则返回空数组。
🌐 The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array.
用法
frame.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 的元素,等待 actionability 检查,直到 <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
frame.select_option("select#colors", "blue")
# single selection matching both the label
frame.select_option("select#colors", label="blue")
# multiple selection
frame.select_option("select#colors", value=["red", "green", "blue"])
# Single selection matching the value or label
await frame.select_option("select#colors", "blue")
# single selection matching the label
await frame.select_option("select#colors", label="blue")
# multiple selection
await frame.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 点击元素的中心。
- 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。
当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
用法
frame.set_checked(selector, checked)
frame.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 是相对路径,则会相对于当前工作目录进行解析。对于空数组,将清除已选的文件。
🌐 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.
此方法期望 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.
用法
frame.set_input_files(selector, files)
frame.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 点击元素的中心,或指定的 位置。
当所有步骤在指定的 timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.
frame.tap() 要求将浏览器上下文的 hasTouch 选项设置为 true。
用法
frame.tap(selector)
frame.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.
用法
frame.text_content(selector)
frame.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 事件。frame.type 可用于发送更精细的键盘事件。要在表单字段中填充值,请使用 frame.fill()。
🌐 Sends a keydown, keypress/input, and keyup event for each character in the text. frame.type can be used to send fine-grained keyboard events. To fill values in form fields, use frame.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 checks 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.
用法
frame.uncheck(selector)
frame.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 满足 state 选项(可以是从 DOM 中出现/消失,或变为可见/隐藏)。如果在调用该方法时 selector 已经满足条件,该方法将立即返回。如果选择器在 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.main_frame.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.main_frame.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.
注意,“frame.waitForTimeout()”仅用于调试。在生产环境中使用定时器的测试会不稳定。使用网络事件、选择器变得可见等信号来代替。
🌐 Note that frame.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.
用法
frame.wait_for_timeout(timeout)
参数
返回