我想将选择器中的所有img传递给img,然后将img的高度推入数组。
现在,我得到一个为每个img返回null的数组。 使用纯Js没问题,但是现在我尝试使其与puppeteer一起使用。
await page.waitForSelector(".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");
heights = [];
imgs = await page.$$(".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");
for(let i = 0; i < imgs.length; i++){
heights.push(imgs[i].height);
}
await page.evaluate(({heights}) => {
console.log(heights);
},{heights});
我希望每个img都具有高度的数组。
我实际上从每个img中都获得了一个带有空值的数组。
答案 0 :(得分:0)
imgs
不会是DOM元素数组,而是Puppeteer ElementHandles。它可以定义为“ DOM指针”。这意味着ElementHandle
将没有height
属性。
如果要获得高度,可以使用$$eval
。
const heights = await page.$$eval(
".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top",
imgs => imgs.map(i => i.height));
第二个参数将是一个函数,期望与该选择器匹配的图像列表。从那里您可以简单地遍历它们。
您还可以将其分为两部分:
const imgs = await page.$$eval(
".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");
const heights = page.eval(imgs => imgs.map(i => i.height), imgs);
答案 1 :(得分:0)
您需要图像的渲染高度吗?如果是这样,您需要使用ElementHandle.boundingBox()
for(let i = 0; i < imgs.length; i++){
heights.push(imgs[i].boundingBox().height);
}