Node.js Cheerio:使用分隔符从HTML中提取文本
假设我有以下几点:Node.js Cheerio:使用分隔符从HTML中提取文本,node.js,cheerio,Node.js,Cheerio,假设我有以下几点: $ = cheerio.load('<html><body><ul><li>One</li><li>Two</li></body></html>'); var t = $('html').find('*').contents().filter(function() { return this.type === 'text'; }).text(); 而不是: O
$ = cheerio.load('<html><body><ul><li>One</li><li>Two</li></body></html>');
var t = $('html').find('*').contents().filter(function() {
return this.type === 'text';
}).text();
而不是:
One Two
如果执行$('html').text()
,得到的结果也是一样的。所以基本上我需要的是注入一个分隔符,比如
(空格)或\n
注意:这不是一个jQuery前端问题,更像是与Cheerio和HTML解析有关的NodeJS后端问题。这似乎可以解决以下问题:
var t = $('html *').contents().map(function() {
return (this.type === 'text') ? $(this).text() : '';
}).get().join(' ');
console.log(t);
结果:
One Two
只是稍微改进了我的解决方案:
var t = $('html *').contents().map(function() {
return (this.type === 'text') ? $(this).text()+' ' : '';
}).get().join('');
您可以使用该包生成html字符串的纯文本版本。您可以在浏览器和node.js中使用它
var createTextVersion = require("textversionjs");
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
var createTextVersion=require(“textversionjs”);
var yourHtml=“你的HTML- 在这里。
- ”;
var textVersion=createTextVersion(yourHtml);
例如,从下载并要求使用Browserify。您可以使用以下函数从由
空格分隔的html中提取文本:
function extractTextFromHtml(html: string): string {
const cheerioStatic: CheerioStatic = cheerio.load(html || '');
return cheerioStatic('html *').contents().toArray()
.map(element => element.type === 'text' ? cheerioStatic(element).text().trim() : null)
.filter(text => text)
.join(' ');
}
…content().toArray().map(元素=>{})。将toArray()应用于内容后,它对我起了作用。谢谢这个解决方案工作得很好,直到页面主体中有内联javascript,出于某种原因,它将内联javascript引入。你知道怎么解决吗?
function extractTextFromHtml(html: string): string {
const cheerioStatic: CheerioStatic = cheerio.load(html || '');
return cheerioStatic('html *').contents().toArray()
.map(element => element.type === 'text' ? cheerioStatic(element).text().trim() : null)
.filter(text => text)
.join(' ');
}