如何使用 cheerio 遍历嵌套的 'div' 元素
how to loop through nested 'div' elements using cheerio
我正在尝试修改 HTML 中的每个 <div>
元素,方法是使用 cheerio 将其换行。
输入:
<html>
<body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
预期输出:
<html>
<body>
<div>
<div>
<div>Hi</div>
</div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
我得到的输出:
<html><head></head><body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body></html>
问题:它没有向嵌套的 <div>
元素添加新行。尝试使用 $(this)
上下文但没有用。
代码:
const c = require('cheerio')
const $ = c.load(html);
$('div').each((i,e) => {
let mod = `\n ${ c.html($(e)) } \n`
$(e).replaceWith(mod)
})
console.log($.html())
你可以这样做:
$('div').before("\n").after("\n")
我正在尝试修改 HTML 中的每个 <div>
元素,方法是使用 cheerio 将其换行。
输入:
<html>
<body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
预期输出:
<html>
<body>
<div>
<div>
<div>Hi</div>
</div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body>
</html>
我得到的输出:
<html><head></head><body>
<div>
<div><div>Hi</div></div>
<div>hello</div>
<div>ur awesome</div>
</div>
</body></html>
问题:它没有向嵌套的 <div>
元素添加新行。尝试使用 $(this)
上下文但没有用。
代码:
const c = require('cheerio')
const $ = c.load(html);
$('div').each((i,e) => {
let mod = `\n ${ c.html($(e)) } \n`
$(e).replaceWith(mod)
})
console.log($.html())
你可以这样做:
$('div').before("\n").after("\n")