使用puppeteer,如何获得节点的所有子节点? [英] Using puppeteer how do you get all child nodes of a node?

查看:600
本文介绍了使用puppeteer,如何获得节点的所有子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找到一种方法来遍历puppeteer中给定节点的子节点时遇到了麻烦.我事先不知道html结构,只知道父元素的ID.

I'm having trouble finding a way to iterate subnodes of a given node in puppeteer. I do not know the html structure beforehand, just the id of the parent element.

var elemId = "myelemid";

const doc = await page._client.send('DOM.getDocument');
const node = await page._client.send('DOM.querySelector', {
    nodeId: doc.root.nodeId,
    selector: '#' + elemId
});
//node.children empty
//node['object'].children empty

//try requesting childnodes
var id = node.nodeId;   
var childNodes = await page._client.send('DOM.requestChildNodes', {
   nodeId: id
});         
//childNodes empty

//try requesting by resolveNode?
var aNode = await page._client.send('DOM.resolveNode', {
   nodeId: id
});      
//aNode.children is empty

如果您不知道puppeteer中的html结构,是否可以获取节点的子代?

Is there a way to get the children of a node if you don't know the html structure in puppeteer?

推荐答案

我最终使用page.evaluate运行一些js,这些js向要分析的每个元素和子元素添加了唯一的类名,然后将其作为JSON字符串从页面传回.evaluate只返回一个字符串.然后,我只在每个唯一选择器上调用DOM.querySelector,并以此方式遍历它们.

I ended up using page.evaluate to run some js that adds unique classnames to every element and subelement I want analyzed and then pass that back as JSON string since page.evaluate only returns a string. Then I just call DOM.querySelector on each of those unique selectors and loop through them that way.

从页面返回子代.$ eval不会给我提供可以在其上运行更多dev协议功能的协议节点,并且xpath不能解决我的真正问题,因为它无法递归地遍历所有子子代,然后这些孩子的子孩子.

Returning children from page.$eval doesn't give me protocol nodes that I can run more dev protocol functions on, and xpath doesn't solve my real problem because it can't recursively loop through all sub-children, then the sub-children of those children.

我正在解决此问题,因为使用唯一的类名进行标记可以解决我的问题.

I'm closing the issue since labeling using unique classnames solves my problem.

这篇关于使用puppeteer,如何获得节点的所有子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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