我使用JSDOM来设置用于处理的html。
async function processHtml(input) {
const dom = new JSDOM(input)
const tables = dom.window.document.getElementsByTagName('tbody')
for (let x of tables) {
if (x.getElementsByTagName('tr').length === 1) {
const test = [...x.getElementsByTagName('tr')]
console.log("Line 32:", test)
} else {
console.log("Line 32:", x.getElementsByTagName('tr').length)
}
}
}我从这个算法中得到的是:
Line 32: HTMLTableRowElement {}
Line 32: 11
Line 32: 10
Line 32: 10
Line 32: HTMLTableRowElement {}
Line 32: HTMLTableRowElement {}
Line 32: 11
Line 32: 12
Line 32: 3
Line 32: HTMLTableRowElement {} 我卡住了。这些不是普通的对象?我该怎么处理呢?
Note
如何在HTMLTableRowElement { }上使用DOM方法?
更新1:更改函数
我想看看我在做什么。
async function processHtml(input) {
const dom = new JSDOM(input)
const tables = dom.window.document.getElementsByTagName('tbody')
Object.keys(tables).forEach(x => console.log(tables[x]))
}此函数返回:
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}
HTMLTableSectionElement {}看来这是一种模式。我不知道有什么工具可以帮助我正确地处理这个问题。
关于如何解决这一问题,我们将不胜感激。谢谢。
更新2:如果其他人发现这个问题有用
这个算法使我更接近于我所寻求的解决方案。多亏了被接受的答案。
async function processHtml(input) {
const dom = new JSDOM(input)
Array.from(dom.window.document.querySelectorAll('table tbody')).forEach((tbody, i) => {
if (i === 4 || i === 5) {
console.log(`========= ${i} ============`)
Array.from(tbody.querySelectorAll('td')).forEach((td, j) => {
if (j === 0 || j === 1){
console.log(`[${j}]`, td.innerHTML)
}
})
console.log('===========================')
}
})发布于 2021-08-29 20:48:33
你有一些选择。首先,如果您想使用它们的默认迭代行为来迭代它们,那么您需要像以前一样使用for of。
如果还想使用数组方法,可以通过以下方法将NodeList或HTMLLiveCollection转换为数组:
Array.prototype.slice.call(...)Array.from(...)Array.from(document.querySelectorAll('table tbody')).forEach(tbody=>{
//do something with tbody
Array.from(tbody.querySelectorAll("tr")).forEach(tr => {
//do something with tr
})
})在上面的示例中,将document更改为dom.window.document,如果愿意,可以使用getElementsByTagName方法。
getElementsByClassName和getElementsByTagName返回活动HTMLCollection,这意味着返回的对象类似于数组,而不是数组,并且在更改DOM时会得到更新。querySelectorAll返回一个NodeList,类似于HTMLCollection,但不更新。它们都有传统的方法,如item,可以按索引获取节点,但我建议先将它们转换为数组。
在上面的示例中,您也可以使用forEach并检查给定项tagName属性是否等于TR,而不是内部的TR循环,并进行相应的操作。
发布于 2021-08-29 19:33:29
let x of tables将循环遍历all的值--对象的可枚举属性,包括诸如length之类的内容。将of切换到in以获取名称。
你只需要数字索引。使用常规的for (let i = 0; i < x.length; i++)循环。
https://stackoverflow.com/questions/68976251
复制相似问题