getAttribute(selector, name[, options])
警告
请改用基于 locator 的
locator.getAttribute()
方法。
返回给定属性名的元素属性值。
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
selector | string | '' | 用于搜索元素的 selector。如果存在多个满足 selector 的元素,将使用第一个。 |
name | string | '' | 要获取其值的属性名。 |
options | object | null | |
options.strict | boolean | false | 当为 true 时,调用要求 selector 解析为单个元素。如果给定的 selector 解析为多个元素,则会抛出异常。 |
options.timeout | number | 30000 | 最大超时时间(毫秒)。传入 0 以禁用超时。默认值会被 BrowserContext 或 Page 上的 setDefaultTimeout 选项覆盖。 |
返回值
类型 | 描述 |
---|---|
Promise<string | null> | 一个 Promise,其状态变为 fulfilled 时包含属性值。否则,返回 null 。 |
示例
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.goto('https://test.k6.io/browser.php');
const attribute = await page.getAttribute('#text1', 'onfocus');
console.log(attribute); // prints inputTextOnFocus();
}