【问题标题】:Cheerio: Extract Text from HTML with separatorsCheerio:使用分隔符从 HTML 中提取文本
【发布时间】:2015-10-11 04:00:08
【问题描述】:

假设我有以下内容:

$ = 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(); 

我明白了:

OneTwo

代替:

One Two

如果我执行$('html').text(),我会得到相同的结果。所以基本上我需要的是注入像(空格)或\n这样的分隔符

注意:这不是一个 jQuery 前端问题,更像是与 Cheerio 和 HTML 解析相关的 NodeJS 后端问题。

【问题讨论】:

    标签: node.js cheerio


    【解决方案1】:

    这似乎可以解决问题:

    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('');
    

    【讨论】:

    • 此解决方案运行良好,直到页面正文中有内​​联 javascript,由于某种原因它被拉入。知道如何解决吗?
    【解决方案2】:

    您可以使用TextVersionJS 包生成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);
    

    npm 下载它,并使用 Browserify 来获取它。

    【讨论】:

      【解决方案3】:

      您可以使用以下函数从以whitespace 分隔的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(element => {}) 。将 toArray() 应用于内容后,它对我有用。谢谢!
      猜你喜欢
      • 2023-03-18
      • 2023-03-31
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      相关资源
      最近更新 更多