【问题标题】:Extract only text content from a web page仅从网页中提取文本内容
【发布时间】:2015-09-28 23:01:26
【问题描述】:
我需要从网页中提取所有文本内容。我用过'document.body.textContent'。
但我也得到了 javascript 内容。如何确保我只得到可读的文本内容?
function myFunction() {
var str = document.body.textContent
alert(str);
}
<html>
<title>Test Page for Text extraction</title>
<head>I hope this works</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<p>Test on this content to change the 5th word to a link
<p>
<button onclick="myFunction()">Try it</button>
</body>
</hmtl>
【问题讨论】:
标签:
javascript
jquery
html
【解决方案1】:
在做body.textContent之前删除你不想读的标签。
function myFunction() {
var bodyScripts = document.querySelectorAll("body script");
for(var i=0; i<bodyScripts.length; i++){
bodyScripts[i].remove();
}
var str = document.body.textContent;
document.body.innerHTML = '<pre>'+str+'</pre>';
}
<html>
<title>Test Page for Text extraction</title>
<head>I hope this works</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<p>Test on this content to change the 5th word to a link
<p>
<button onclick="myFunction()">Try it</button>
</body>
</hmtl>