我正在尝试检测/抓取
标记中包含< span >标记的句子。我想要得到一组句号之间的整个句子。这必须为整个网页做。
例如,下面的段落包含我想要提取的span句子:
<p>The phospholipid heads face outward, one layer exposed to the interior of the cell and one layer exposed to the exterior. Because the <span>phosphate</span> groups are polar and hydrophilic, they are attracted to water in the intracellular fluid. Intracellular fluid (ICF) is the fluid interior of the cell.</p> 我只想提取一句话:“因为磷酸基团是极性的和亲水性的,所以它们被细胞内液体中的水所吸引”,因为它包含标签
我可以对整个网页执行此操作吗?使用regex还是js?
我在网上尝试过不同的正则表达式组合,但它们都不起作用。
发布于 2019-09-01 05:47:38
for(const span of document.querySelectorAll("p span")) {
const prevText = span.previousSibling.data;
const afterText = span.nextSibling.data;
const prev = prevText.slice( prevText.lastIndexOf(".") );
comst after = afterText.slice(0, afterText.indexOf("."));
// do whatever you wanna do here
}使用DOM的方法,您可以遍历<p>中的所有<span>,并分别使用previousSibling和nextSibling访问它之前和之后的文本。要获得围绕它的“句子”,请使用。把句子分开。
到目前为止,这还没有完成,可能有前一个或下一个节点不是文本节点的情况,或者这些文本节点中没有点的情况。你必须适当地处理这些情况。
请参见:
发布于 2019-09-01 05:42:47
您可以使用JavaScript。让我们将句子存储在一个数组中。
句子:
<p>The sun is <span>shining</span> today</p>
<p>Let's refactorate it</p>
<p>Nice. It's a <span>special day</span> of celebration</p>JavaScript:
var sentences = [];
document.querySelectorAll('p span').forEach(function(span) {
var sentencesText = span.parentNode.innerText.split('.');
span.parentNode.innerHTML.split('.').forEach(function(sent, i) {
if (sent.indexOf("<span>") != -1) {
sentences.push(sentencesText[i]);
}
})
});sentences数组的结果:
"The sun is shining today"
"It's a special day of celebration"发布于 2019-09-01 06:12:47
使用split方法分隔句子,然后搜索有span的句子
const p=document.getElementsByTagName('p')[0].innerHTML;
p.split(".").forEach(e=>{
if(e.indexOf('span')>0){
console.log(e);
}
});<p>The phospholipid heads face outward, one layer exposed to the interior of the cell and one layer exposed to the exterior. Because the <span>phosphate</span> groups are polar and hydrophilic, they are attracted to water in the intracellular fluid. Intracellular fluid (ICF) is the fluid interior of the cell.</p>
https://stackoverflow.com/questions/57741743
复制相似问题