评估 JavaScript
简介
Playwright 脚本在您的 Playwright 环境中运行。您的页面脚本在浏览器页面环境中运行。这些环境互不相交,它们在不同的虚拟机、不同的进程中运行,甚至可能在不同的计算机上运行。
page.evaluate()
API 可以在网页的上下文中运行 JavaScript 函数,并将结果返回到 Playwright 环境。浏览器全局变量(如 window
和 document
)可以在 evaluate
中使用。
- 同步
- 异步
href = page.evaluate('() => document.location.href')
href = await page.evaluate('() => document.location.href')
如果结果是 Promise,或者函数是异步的,evaluate 将自动等待直到它被解析
- 同步
- 异步
status = page.evaluate("""async () => {
response = await fetch(location.href)
return response.status
}""")
status = await page.evaluate("""async () => {
response = await fetch(location.href)
return response.status
}""")
不同的环境
评估的脚本在浏览器环境中运行,而您的测试在测试环境中运行。这意味着您不能在页面中使用测试中的变量,反之亦然。相反,您应该将它们作为参数显式传递。
以下代码片段是错误的,因为它直接使用了变量
- 同步
- 异步
data = "some data"
result = page.evaluate("""() => {
// WRONG: there is no "data" in the web page.
window.myApp.use(data)
}""")
data = "some data"
result = await page.evaluate("""() => {
// WRONG: there is no "data" in the web page.
window.myApp.use(data)
}""")
以下代码片段是正确的,因为它将值作为参数显式传递
- 同步
- 异步
data = "some data"
# Pass |data| as a parameter.
result = page.evaluate("""data => {
window.myApp.use(data)
}""", data)
data = "some data"
# Pass |data| as a parameter.
result = await page.evaluate("""data => {
window.myApp.use(data)
}""", data)
评估参数
Playwright 评估方法(如 page.evaluate()
)接受一个可选参数。此参数可以是 可序列化 值和 JSHandle 实例的混合。句柄会自动转换为它们代表的值。
- 同步
- 异步
# A primitive value.
page.evaluate('num => num', 42)
# An array.
page.evaluate('array => array.length', [1, 2, 3])
# An object.
page.evaluate('object => object.foo', { 'foo': 'bar' })
# A single handle.
button = page.evaluate_handle('window.button')
page.evaluate('button => button.textContent', button)
# Alternative notation using JSHandle.evaluate.
button.evaluate('(button, from) => button.textContent.substring(from)', 5)
# Object with multiple handles.
button1 = page.evaluate_handle('window.button1')
button2 = page.evaluate_handle('.button2')
page.evaluate("""o => o.button1.textContent + o.button2.textContent""",
{ 'button1': button1, 'button2': button2 })
# Object destructuring works. Note that property names must match
# between the destructured object and the argument.
# Also note the required parenthesis.
page.evaluate("""
({ button1, button2 }) => button1.textContent + button2.textContent""",
{ 'button1': button1, 'button2': button2 })
# Array works as well. Arbitrary names can be used for destructuring.
# Note the required parenthesis.
page.evaluate("""
([b1, b2]) => b1.textContent + b2.textContent""",
[button1, button2])
# Any mix of serializables and handles works.
page.evaluate("""
x => x.button1.textContent + x.list[0].textContent + String(x.foo)""",
{ 'button1': button1, 'list': [button2], 'foo': None })
# A primitive value.
await page.evaluate('num => num', 42)
# An array.
await page.evaluate('array => array.length', [1, 2, 3])
# An object.
await page.evaluate('object => object.foo', { 'foo': 'bar' })
# A single handle.
button = await page.evaluate_handle('button')
await page.evaluate('button => button.textContent', button)
# Alternative notation using JSHandle.evaluate.
await button.evaluate('(button, from) => button.textContent.substring(from)', 5)
# Object with multiple handles.
button1 = await page.evaluate_handle('window.button1')
button2 = await page.evaluate_handle('window.button2')
await page.evaluate("""
o => o.button1.textContent + o.button2.textContent""",
{ 'button1': button1, 'button2': button2 })
# Object destructuring works. Note that property names must match
# between the destructured object and the argument.
# Also note the required parenthesis.
await page.evaluate("""
({ button1, button2 }) => button1.textContent + button2.textContent""",
{ 'button1': button1, 'button2': button2 })
# Array works as well. Arbitrary names can be used for destructuring.
# Note the required parenthesis.
await page.evaluate("""
([b1, b2]) => b1.textContent + b2.textContent""",
[button1, button2])
# Any mix of serializables and handles works.
await page.evaluate("""
x => x.button1.textContent + x.list[0].textContent + String(x.foo)""",
{ 'button1': button1, 'list': [button2], 'foo': None })
初始化脚本
有时在页面开始加载之前评估某些内容是很方便的。例如,您可能想要设置一些模拟或测试数据。
在这种情况下,请使用 page.add_init_script()
或 browser_context.add_init_script()
。在下面的示例中,我们将把 Math.random()
替换为一个常量值。
首先,创建一个包含模拟的 preload.js
文件。
// preload.js
Math.random = () => 42;
接下来,将初始化脚本添加到页面。
- 同步
- 异步
# In your test, assuming the "preload.js" file is in the "mocks" directory.
page.add_init_script(path="mocks/preload.js")
# In your test, assuming the "preload.js" file is in the "mocks" directory.
await page.add_init_script(path="mocks/preload.js")