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

Node.js环境下Selenium WebDriver获取元素尺寸报错,求正确方法

正确获取元素尺寸的方法(Node.js + Selenium-Webdriver)

嘿,我来帮你搞定这个问题!你遇到的TypeError: driver.getElementSize is not a function错误,是因为Node.js版本的selenium-webdriver里根本没有driver.getElementSize()这个方法。想要获取元素的尺寸,正确的思路是先定位到目标元素,再调用元素自身的getSize()方法,而且要注意Selenium的操作全是异步的,得用async/await或者Promise链式调用处理异步逻辑。

方法1:用async/await(推荐,代码更易读)

这是现在Node.js里处理异步最常用的方式,代码逻辑清晰:

const { Builder, By } = require('selenium-webdriver');

async function getElementSize() {
  // 初始化浏览器驱动(这里以Chrome为例)
  let driver = await new Builder().forBrowser('chrome').build();
  try {
    // 打开目标页面
    await driver.get('你的目标网页URL');
    // 定位到目标元素
    const targetElem = await driver.findElement(By.xpath("//some_path"));
    // 获取元素尺寸,返回包含width和height的对象
    const elemSize = await targetElem.getSize();
    // 提取宽高
    const elemWidth = elemSize.width;
    const elemHeight = elemSize.height;
    console.log(`元素宽度:${elemWidth}px,高度:${elemHeight}px`);
  } finally {
    // 不管成功失败,都关闭浏览器
    await driver.quit();
  }
}

// 调用函数执行
getElementSize();

方法2:用Promise链式调用

如果你更习惯Promise的写法,也可以这样实现:

const { Builder, By } = require('selenium-webdriver');

new Builder().forBrowser('chrome').build()
  .then(driver => {
    return driver.get('你的目标网页URL')
      // 定位元素
      .then(() => driver.findElement(By.xpath("//some_path")))
      // 获取尺寸
      .then(elem => elem.getSize())
      // 处理结果
      .then(size => {
        console.log(`元素宽度:${size.width}px,高度:${size.height}px`);
      })
      // 最后关闭浏览器
      .finally(() => driver.quit());
  })
  // 捕获错误
  .catch(err => console.error('执行出错:', err));

关键注意点

  • 所有和驱动交互的操作(比如findElement、getSize)都返回Promise,绝对不能像同步代码那样直接赋值调用,必须等待异步操作完成才能拿到结果。
  • Node.js版Selenium里,getSize()直接返回包含width和height的普通对象,不需要调用getWidth()——这个方法是Java版Selenium里的,别搞混啦!

内容的提问来源于stack exchange,提问作者Brenda Olivia Martis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:29:16