簡體   English   中英

從 html 響應 nodejs 中提取文本值

[英]extract the text values from html response nodejs

我有一個場景,我試圖在 html 中提取以下文本的值並存儲在一個變量中。 截至目前,我已經嘗試過Cheerio但它似乎不起作用。

HTML:

var htmlbody = <table style="width:100%; border: 1px solid #cccccc; border-collapse: collapse;" border=1 cellspacing="0" cellpadding="4"><tr><td style="background-color: #eeeeee; width: 200px;">Improvement Date (first date)</td><td>Nov 5, 2019 1:57:00 PM UTC</td></tr><tr><td style="background-color: #eeeeee">Document Call existed at</td><td>Nov 5, 2019 3:40:00 PM UTC</td></tr><tr><td style="background-color: #eeeeee">Document creation at</td><td>not available</td></tr><tr><td style="background-color: #eeeeee; width: 200px;">First document sent</td><td>not available</td></tr></table>

我在這里嘗試過的

   const cheerio = require('cheerio')
   var html = htmlbody
   const txt = $(html).text()
   console.log(txt)

我想以精確的順序從 html 中單獨提取以下值,並單獨存儲在變量中。

Nov 5, 2019 1:57:00 PM UTC
Nov 5, 2019 3:40:00 PM UTC
not available
not available

注意:我擁有的 HTML 片段不會分配任何 class 或 id。

這可以通過解析內容來實現。 請參考下面的代碼。

const cheerio = require('cheerio');

var htmlbody = '<table style="width:100%; border: 1px solid #cccccc; border-collapse: collapse;" border=1 cellspacing="0" cellpadding="4"><tr><td style="background-color: #eeeeee; width: 200px;">Improvement Date (first date)</td><td>Nov 5, 2019 1:57:00 PM UTC</td></tr><tr><td style="background-color: #eeeeee">Document Call existed at</td><td>Nov 5, 2019 3:40:00 PM UTC</td></tr><tr><td style="background-color: #eeeeee">Document creation at</td><td>not available</td></tr><tr><td style="background-color: #eeeeee; width: 200px;">First document sent</td><td>not available</td></tr></table>';

const $ = cheerio.load(htmlbody);

var html = $('table').children();
var tr = $("tr", html);
var val = {};
for(var i = 0; i < tr.length; i++) {
    var td = $("td", tr[i]);
    val[$(td[0]).html()] = $(td[1]).html();
}
// The extracted values are stored in key value pair
// 'Improvement Date (first date)': 'Nov 5, 2019 1:57:00 PM UTC',
// 'Document Call existed at': 'Nov 5, 2019 3:40:00 PM UTC',
// 'Document creation at': 'not available',
// 'First document sent': 'not available'
console.log(val);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM