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

Selenium 4中withTagName方法未定义报错问题求助

解决Selenium 4相对定位器withTagName未定义的报错

你遇到的ReferenceError: withTagName is not defined报错,核心原因是没有从selenium-webdriver模块中正确导入withTagName方法,另外代码里混合使用async/await和.then()也可能引发Promise未处理的警告,下面是具体的修复步骤:

1. 导入withTagName方法

在你顶部的解构导入语句中,需要添加withTagName:

const { Builder, By, Key, util, withTagName } = require("selenium-webdriver")

withTagName是Selenium 4相对定位器的核心方法之一,必须显式导入才能使用。

2. 统一使用async/await简化代码

你的代码里混合了async/await和.then(),这不仅会让代码可读性下降,还容易出现未处理的Promise拒绝警告。建议统一用async/await重构:

修改后的完整代码:

const { Builder, By, withTagName } = require("selenium-webdriver")
const until = require("selenium-webdriver/lib/until")
const firefox = require("selenium-webdriver/firefox")

async function run() {
  let driver = null;
  try {
    driver = await new Builder().forBrowser("firefox").build()
    await driver.get("https://www.google.com")
    
    // 等待目标元素加载
    const titleElement = await driver.wait(until.elementLocated(By.className("lnXdpd")), 4000);
    // 使用相对定位器查找下方的div元素
    const targetElement = await driver.findElement(withTagName("div").below(titleElement));
    
    console.log("找到目标元素!");
  } catch (err) {
    console.warn("操作失败:", err.message);
  } finally {
    // 确保浏览器始终关闭
    if (driver) await driver.quit();
  }
}

run()

3. 版本兼容性确认

你使用的selenium-webdriver@4.0.0-beta.4确实已经支持相对定位器功能,但如果后续仍有问题,可以考虑升级到Selenium 4的稳定版本,执行:

npm update selenium-webdriver

这样修改后,就能解决withTagName未定义的问题,同时代码结构更清晰,也能避免Promise相关的警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:23:13