Selenium操作New Relic时getAttribute返回ManagedPromise无法取属性值怎么办
问题根因
你得到的输出是ManagedPromise实例,Selenium WebDriver的getAttribute()属于异步操作,会直接返回Promise对象而非实际属性值。你直接打印时Promise还处于pending(未完成)状态,因此无法拿到目标属性数据。
解决方法
- 方案1:使用async/await语法(推荐,New Relic Synthetic运行环境原生支持)
将操作逻辑放在async函数内,使用await等待异步操作完成后再访问结果,示例代码如下:
// 引入必要依赖 const { By } = require('selenium-webdriver'); // 脚本逻辑标记为async async function getElementAttr() { // 等待找到目标元素 const targetElement = await driver.findElement(By.id('替换为你的元素ID')); // 等待获取属性的异步操作完成,拿到实际属性值 const elementId = await targetElement.getAttribute('id'); // 此时打印即可得到实际属性值 console.log(elementId); } // 执行函数 getElementAttr();
New Relic Synthetics脚本支持直接在顶层使用await,也可以简化写法:
const targetElement = await driver.findElement(By.id('替换为你的元素ID')); const elementId = await targetElement.getAttribute('id'); console.log(elementId);
- 方案2:使用Promise .then回调处理
如果你不想用async/await语法,也可以通过.then回调拿到Promise完成后的结果:
const { By } = require('selenium-webdriver'); driver.findElement(By.id('替换为你的元素ID')) .then(element => element.getAttribute('id')) .then(elementId => { // 回调内即可拿到实际属性值 console.log(elementId); });
注意事项
- 操作元素前建议添加显式等待,确保元素已经完成加载,避免出现找不到元素的异常,示例如下:
const { By, until } = require('selenium-webdriver'); // 最长等待10秒,直到元素出现在DOM中 const targetElement = await driver.wait(until.elementLocated(By.id('替换为你的元素ID')), 10000); const elementId = await targetElement.getAttribute('id'); console.log(elementId);
- 所有Selenium异步操作的返回值都需要等待Promise完成后再访问,禁止直接打印方法返回的Promise对象。
内容的提问来源于stack exchange,提问作者Richard Aguirre
相关产品推荐
相关产品推荐

