从 Table.getProperties('childNodes/children') 中提取子节点
Extracting childNodes from Table.getProperties('childNodes/children')
所以我在尝试抓取 web-table 时遇到了这个问题。我能够通过使用 'firstChild' 和 'lastElementChild' 作为单个子节点来提取 table 节点。我的问题是我想提取地图或数组中的所有子节点(rows/cells),这样我就可以循环迭代和提取数据。
注意:我使用的是 puppeteer,因此使用 ASYNC 函数
这是一个代码片段:
const [table] = await page.$x(xpath);
const tbody = await table.getProperty('lastElementChild'); //<-- in this case tbody is lastchild
const rows = Array.from(await tbody.getProperties('childNodes')); // <-- LINE OF THE PROBLEM
const cell = await rows.getProperty('firstChild') // <-- using firstChild for testing (ideally 'childNodes' with forEach())
const data = await cell.getProperty('innerText');
const txt = await data.jsonValue();
console.log(txt);
我找到了另一种方法...
解决方法如下:
const row = await page.evaluate(() => {
let row = document.querySelector('.fluid-table__row'); //<-- this refers to a HTML class
let cells = [];
row.childNodes.forEach(function(cell){
cells.push(cell.textContent)
})
return cells;
})
console.log(row);
所以我在尝试抓取 web-table 时遇到了这个问题。我能够通过使用 'firstChild' 和 'lastElementChild' 作为单个子节点来提取 table 节点。我的问题是我想提取地图或数组中的所有子节点(rows/cells),这样我就可以循环迭代和提取数据。
注意:我使用的是 puppeteer,因此使用 ASYNC 函数
这是一个代码片段:
const [table] = await page.$x(xpath);
const tbody = await table.getProperty('lastElementChild'); //<-- in this case tbody is lastchild
const rows = Array.from(await tbody.getProperties('childNodes')); // <-- LINE OF THE PROBLEM
const cell = await rows.getProperty('firstChild') // <-- using firstChild for testing (ideally 'childNodes' with forEach())
const data = await cell.getProperty('innerText');
const txt = await data.jsonValue();
console.log(txt);
我找到了另一种方法...
解决方法如下:
const row = await page.evaluate(() => {
let row = document.querySelector('.fluid-table__row'); //<-- this refers to a HTML class
let cells = [];
row.childNodes.forEach(function(cell){
cells.push(cell.textContent)
})
return cells;
})
console.log(row);