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

Selenium JavaScript点击元素触发NoSuchElementError,显式等待无效求解决

Selenium JavaScript自动化测试:NoSuchElementError问题求助

我使用Selenium结合JavaScript进行自动化测试时,点击元素出现NoSuchElementError错误,已尝试显式等待但问题仍未解决,恳请技术人员提供帮助。

test.js代码

const Browser = require("../Browser")
const MainPage = require("../pageobjects/MainPage")
const AlertPage = require("../pageobjects/AlertPage");
describe("Test 1", function(){
    it("test case",  async function(){
         await Browser.goToUrl("https://demoqa.com/")
         let mainPage = new MainPage();
         let isMainPageDisplayed = await mainPage.isMainPageDisplayed();
         expect(isMainPageDisplayed).to.be.true
         await mainPage.clickAlertFrameWindows()
         let alertPage = new AlertPage()
         let isAlertPageDisplayed = await alertPage.isAlertElDisplayed();
         expect(isAlertPageDisplayed).to.be.true
         await alertPage.clickAlertEl()
         await Browser.closeBrowser()
    })
})

AlertPage.js代码

class AlertPage{
    #name = "Alert Page";
    #locator = "//span[text()='Alerts']"
    #alertEl = new BaseElement(this.#locator, "Alert button")

    clickAlertEl(){
 BrowserFactory.getBrowser().wait(until.elementLocated(By.xpath("//span[text()='Alerts']/ancestor::li[contains(@class,'btn')]")))
        this.#alertEl.clickWithExecutor()
 
    }
    isAlertElDisplayed(){
        // BrowserFactory.getBrowser().wait(until.elementLocated(By.xpath("//span[text()='Alerts']/ancestor::li[contains(@class,'btn')]")))
        return this.#alertEl.isElementPresent()
    }
}
module.exports = AlertPage;

页面HTML截图

页面截图

问题分析与解决建议

1. 显式等待未处理异步

clickAlertEl方法中的wait是异步操作,但未添加await,导致代码跳过等待直接执行点击,此时元素可能还未加载完成。需将方法改为异步并添加await:

async clickAlertEl(){
    await BrowserFactory.getBrowser().wait(until.elementLocated(By.xpath("//span[text()='Alerts']/ancestor::li[contains(@class,'btn')]")))
    await this.#alertEl.clickWithExecutor()
}

2. 定位器不一致

等待的是li元素,但实际点击的是其子元素span。建议统一定位器,或确保点击的元素在等待完成后确实可见,可修改等待条件为元素可见:

await BrowserFactory.getBrowser().wait(until.elementIsVisible(By.xpath("//span[text()='Alerts']")))

3. 页面切换后的等待

点击Alert Frame Windows后,页面可能存在侧边栏展开或元素渲染的过程,需在实例化AlertPage前添加等待,确保目标元素已加载完成。

4. isAlertElDisplayed方法优化

isElementPresent仅判断元素是否存在于DOM中,不代表元素可见。建议改为等待元素可见后再返回结果:

async isAlertElDisplayed(){
    await BrowserFactory.getBrowser().wait(until.elementIsVisible(By.xpath(this.#locator)))
    return this.#alertEl.isDisplayed()
}

内容的提问来源于stack exchange,提问作者Azizbek Khakimov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:20:41