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

Gab*_*eno 5 puppeteer

我正在尝试使用Puppeteer获取ElementHandle的类名称...可能吗?我使用错误的方法吗?在此jsBin是我的代码的一部分,因此您可以了解我要实现的目标。

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 )
}
Run Code Online (Sandbox Code Playgroud)

https://jsbin.com/kuzejoluji/edit?js,输出

谢谢:D

小智 7

由于此页面当前是第一个搜索“ elementhandle类名”的结果,因此将其放置在此处

文档中,您应该能够执行以下操作

const el = await page.$('.myElement')
const className = await el.getProperty('className')

// alternatively,
// page.$('.myElement')
//    .then(el => el.getProperty('className'))
//    .then(className => ... )
Run Code Online (Sandbox Code Playgroud)

  • 在较新的 API 中,您还需要调用 `jsonValue()`,因为 `getProperty()` 返回一个 JSHandle(请参阅 [docs](https://pptr.dev/#?product=Puppeteer&amp;version=v5.5.0&amp;show=api-elementhandlegetpropertypropertyname ))。获取类: `const className = wait (await el.getProperty('className')).jsonValue()` (5认同)

Dan*_*iel 6

jimmyjoy的答案是正确的,但这可能有助于其他人使用elementHandle

  page.$(el) // This grabs the element (returns a elementHandle)
    .then((el) => el.getProperty("className")) // Returns a jsHandle of that property
    .then((cn) => cn.jsonValue()) // This converts the className jsHandle to a space delimitedstring       
    .then((classNameString) => classNameString.split(" ") // Splits into array
    .then((x) => console.log(x)
Run Code Online (Sandbox Code Playgroud)

这将记录一个类的数组

注意:当我尝试在jsonValue()的末尾执行.split时,此方法不起作用,因为我认为该点尚未解决诺言,因此将cn.jsonValue().split(" ")不起作用


参考文献

元素属性列表

适用于ElementHandle的Puppeteer文档


Gab*_*eno 5

我找到了一个在某些方面有帮助的解决方案,但它对我来说已经足够好了。我已经获得了类名 accessing ElementHandle._remoteObject.description。希望这对某人有帮助。