Max*_*Max 4 html screen-scraping text-extraction html-content-extraction
我正在研究一种算法,在给定HTML文件的情况下,它会尝试选择它认为最有可能包含页面大部分内容文本的父元素.例如,它将在以下HTML中选择div"content":
<html>
<body>
<div id="header">This is the header we don't care about</div>
<div id="content">This is the <b>Main Page</b> content. it is the
longest block of text in this document and should be chosen as
most likely being the important page content.</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想出了一些想法,比如遍历HTML文档树到它的叶子,加上文本的长度,只看到父母给我们的内容比孩子更多的其他文本.
有没有人尝试过这样的东西,或者知道可以应用的算法?它不必是可靠的,但只要它能猜出包含大部分页面内容文本的容器(例如文章或博客文章),那就太棒了.
以下是我将如何处理这个问题:
// get array of all elements (body is used as parent here but you could use whatever)
var elms = document.body.getElementsByTagName('*');
var nodes = Array.prototype.slice.call( elms, 0 );
// get inline elements out of the way (incomplete list)
nodes = nodes.filter(function (elm) {
return !/^(a|br?|hr|code|i(ns|mg)?|u|del|em|s(trong|pan))$/i.test( elm.nodeName );
});
// sort elements by most text first
nodes.sort(function(a,b){
if (a.textContent.length == b.textContent.length) return 0;
if (a.textContent.length > b.textContent.length) return -1;
return 1;
});
Run Code Online (Sandbox Code Playgroud)
使用类似的祖先函数a.compareDocumentPosition(b),您还可以在排序期间(或之后)接收元素,具体取决于此事物需要的复杂程度.