如何通过 Puppeteer 获取元素的孩子 [英] How to get children of elements by Puppeteer

查看:241
本文介绍了如何通过 Puppeteer 获取元素的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 puppeteer 有自己的句柄而不是标准的 DOM 元素,但我不明白为什么我不能通过找到的元素继续相同的查询>

I understand that puppeteer get its own handles rather than standard DOM elements, but I don't understand why I cannot continue the same query by found elements as

const els = await page.$$('div.parent');

for (let i = 0; i < els.length; i++) {
    const img = await els[i].$('img').getAttribute('src');
    console.log(img);
    const link = await els[i].$('a').getAttribute('href');
    console.log(link);
}

推荐答案

问题

元素句柄作为 Node.js 和浏览器运行时之间的抽象层是必要的.实际的 DOM 元素不会发送到 Node.js 环境.

Problem

The element handles are necessary as an abstraction layer between the Node.js and browser runtime. The actual DOM elements are not sent to the Node.js environment.

这意味着当您想从元素获取属性时,必须将数据传输到浏览器(使用哪个 DOM 元素)并返回(结果).

That means when you want to get an attribute from an element, there has to be data transferred to the browser (which DOM element to use) and back (the result).

因此,await els[i].$('img') 的结果并不是真正的 DOM 元素,而只是一个链接到浏览器环境中元素的包装器.要获取该属性,您必须使用像 elementHandle.$eval:

Therefore, the result from await els[i].$('img') is not really the DOM element, but only a wrapper that links to the element in the browser environment. To get the attribute, you have to use a function like elementHandle.$eval:

const imgSrc = await els[i].$eval('img', el => el.getAttribute('src'));

这会在给定元素上运行 querySelector 函数并执行给定函数以返回其属性.

This runs the querySelector function on the given element and executes the given function to return its attribute.

这篇关于如何通过 Puppeteer 获取元素的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆