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

使用Puppeteer时如何获取ElementHandle的类名?

使用Puppeteer获取ElementHandle的类名可行吗?我的方法有问题吗?

当然可行!不过你的代码里确实存在几处需要修正的地方,我帮你梳理一下:

先看你提供的代码(我补全了语法缺失的部分):

CriticalCssPlugin.prototype.load = function( page, src ) {
  return page.goto( src, { waitUntil: 'networkidle2' } )
    .then( () => {
      return page
        .$$( '*' )
        .then( elements => {
          return Promise.all( elements.map( element => {
            return element.boundingBox()
          } ) )
          .then( positions => {
            let visible = positions.filter( ( rect, index ) => {
              if ( !rect ) {
                return rect
              }
              rect.element = elements[ index ]
              return this.isAnyPartOfElementInViewport( rect, page.viewport() )
            } )
            this.getClasses( visible )
          } )
        } )
    } )
}

CriticalCssPlugin.prototype.getClasses = function( visibles ) {
  Promise.all( visibles.map( visible => {
    // 这里传入空字符串是错误的
    return visible.element.getProperty( '' )
  } ) )
  .then( classes => {
    console.log(classes);
  } )
}

CriticalCssPlugin.prototype.isAnyPartOfElementInViewport = function( rect, viewport ) {
  const windowHeight = viewport.height
  const windowWidth = viewport.width
  const vertInView = ( rect.y <= windowHeight ) && ( ( rect.y + rect.height ) >= 0 )
  const horInView = ( rect.x <= windowWidth ) && ( ( rect.x + rect.width ) >= 0 )
  return ( vertInView && horInView )
  // 这里缺少闭合大括号
}

主要问题和修正方案:

  • 获取属性时传入了空字符串
    在getClasses方法里,你调用visible.element.getProperty('')是错误的——要获取类名,需要传入'className'属性名。而且getProperty返回的是JSHandle对象,必须调用jsonValue()才能拿到实际的类名字符串。

    修正后的getClasses方法:

    CriticalCssPlugin.prototype.getClasses = function( visibles ) {
      Promise.all( visibles.map( visible => {
        // 获取className属性并转换为字符串
        return visible.element.getProperty('className').then(handle => handle.jsonValue())
      } ) )
      .then( classes => {
        console.log(classes); // 现在会输出可见元素的类名字符串数组
      } )
    }
    
  • 语法错误:缺少函数闭合括号
    你的isAnyPartOfElementInViewport函数最后少了一个},补全后才能正常运行:

    CriticalCssPlugin.prototype.isAnyPartOfElementInViewport = function( rect, viewport ) {
      const windowHeight = viewport.height
      const windowWidth = viewport.width
      const vertInView = ( rect.y <= windowHeight ) && ( ( rect.y + rect.height ) >= 0 )
      const horInView = ( rect.x <= windowWidth ) && ( ( rect.x + rect.width ) >= 0 )
      return ( vertInView && horInView )
    } // 补上这个闭合括号
    
  • 可选优化:过滤可见元素时的逻辑
    在过滤可见元素的filter回调里,当rect为null时直接返回rect(也就是false)没问题,但可以写成if (!rect) return false;,逻辑会更清晰,避免歧义。

调整完这些之后,你就能成功获取到可见元素的类名数组了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:34:28