我正在尝试使用 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 )
}
https://jsbin.com/kuzejoluji/edit?js,output
谢谢:D
最佳答案
由于此页面当前是搜索“elementhandle class name”的第一个结果,因此将其删除到此处
从 docs ,您应该能够以下
const el = await page.$('.myElement')
const className = await el.getProperty('className')
// alternatively,
// page.$('.myElement')
// .then(el => el.getProperty('className'))
// .then(className => ... )
关于puppeteer - 使用 Puppeteer 时如何获取 ElementHandle 的类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412930/