How to get children of elements by Puppeteer

你离开我真会死。 提交于 2020-07-09 15:42:20

问题


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);
}

回答1:


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.

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).

Solution

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'));

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




回答2:


You can use $eval

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

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


来源:https://stackoverflow.com/questions/55659097/how-to-get-children-of-elements-by-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!