我有一种情况,我试图提取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代码段不会分配任何类或ID。
答案 0 :(得分:1)
这可以通过解析内容来实现。请参考下面的代码。
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);