我想从html中提取文本,命名为text.html,如下
<div class="trans-container">
<ul>
<p class="wordGroup">
<span style="font-weight: bold; color: #959595; margin-right: .5em; width : 36px; display: inline-block;">adj.</span>
<span class="contentTitle"><a class="search-js" href="/w/good/#keyfrom=E2Ctranslation">good</a>
<span style="font-weight: bold; color: #959595;"> ;</span>
</span>
<span class="contentTitle"><a class="search-js" href="/w/fine/#keyfrom=E2Ctranslation">fine</a>
<span style="font-weight: bold; color: #959595;"> ;</span>
</span>
<span class="contentTitle"><a class="search-js" href="/w/ok/#keyfrom=E2Ctranslation">ok</a>
</span>
</p>
<p class="wordGroup">
<span style="font-weight: bold; color: #959595; margin-right: .5em; width : 36px; display: inline-block;">adv.</span>
<span class="contentTitle"><a class="search-js" href="/w/well/#keyfrom=E2Ctranslation">well</a>
</span>
</p>
<p class="wordGroup">
<span style="font-weight: bold; color: #959595; margin-right: .5em; width : 36px; display: inline-block;">misc.</span>
<span class="contentTitle"><a class="search-js" href="/w/all right/#keyfrom=E2Ctranslation">all right</a>
</span>
</p>
</ul>
</div>
并按照以下格式打印出来。
adj. good ; fine ; ok
adv. well
misc. all right
我尝试过的是下面的代码
const cheerio = require('cheerio');
const fs = require('fs');
const $ = cheerio.load(fs.readFileSync('./test.html'));
$('div.trans-container').find('p.wordGroup').each(function(i,elm){
const line = []
$(this).find('span').each(function(i,elm){
line[i] = $(this).text().trim()
})
console.log(line.join(' '))
});
不幸的是,输出如下,并不完全符合我想要的。谁能帮我指出我错在哪里?另外,如果您能为我提供其他好的方法来通过 JavaScript 解决这个问题,无论是否有 Cheerio,我将不胜感激。
adj. good
; ; fine
; ; ok
adv. well
misc. all right
最佳答案
只需在主组上使用text()
,在本例中为.wordGroup
,它将获取元素的所有文本,不包含html元素。然后运行 replace()
来删除所有带有单个空格的空白字符。
$('div.trans-container').find('p.wordGroup').each(function(i,elm){
// regex: /\s+/g matches 1 or more whitespace characters \n\r\f\t
var line = $(this).text().replace(/\s+/g," ");
console.log(line);
});
至于仅使用 native JavaScript 来完成此操作,您无法使用 Nodejs 来完成此操作,因为它没有 native DOM 支持。所以你必须使用 Cheerio 或 jsdom 这样的模块。如果你指的是浏览器中的 javascript,它会是这样的:
document.querySelectorAll('div.trans-container p.wordGroup')
.forEach(ele=>console.log( ele.innerText.replace(/\s+/g," ") ));
关于javascript - 如何通过 JavaScript/cheerio 从以下 html 中提取我想要的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107415/