You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Selenium中Promise { pending }问题?Discord爬虫机器人场景

解决Selenium中getText()返回Promise { Pending }的问题

问题原因

你看到的Promise { Pending }是因为**getText()方法本身返回的是一个Promise**,即使你已经用await获取到了元素对象,调用getText()时仍然需要等待这个Promise完成才能拿到实际文本值。

修复方案

方案1:链式调用并await

直接在获取元素的同时链式调用getText(),并加上await等待结果:

// 修复后的Type获取代码
const Type = await driver.findElement(By.css('div.status')).getText();
console.log('Type:', Type);

方案2:分步获取(更清晰)

先获取元素对象,再单独等待getText()的结果:

// 先获取元素
const statusElement = await driver.findElement(By.css('div.status'));
// 再等待getText()解析完成
const Type = await statusElement.getText();
console.log('Type:', Type);

你之前尝试的代码错误分析

你写的这段代码:

const hi = await driver.findElement(By.css('div.status'))
hi.then((response) =>
{
    console.log(response.getText()
});

错误在于response.getText()仍然返回Promise,你没有等待它解析。可以改成以下两种方式之一:

方式A:链式then处理

const hi = await driver.findElement(By.css('div.status'));
hi.then((response) => {
    return response.getText();
}).then(text => {
    console.log(text);
});

方式B:在then回调中使用await

const hi = await driver.findElement(By.css('div.status'));
hi.then(async (response) => {
    const text = await response.getText();
    console.log(text);
});

额外提示

  • 尽量用const或let声明变量(比如你代码里的Title、ABC、imgSrc都没有声明,容易造成全局变量污染)。
  • Selenium的绝大多数元素操作(如getAttribute()、getText())都是异步的,必须通过await或.then()处理才能拿到实际值。

内容的提问来源于stack exchange,提问作者Bob Toby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:10:32