首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检测句点之间包含<span>标记的<p>标记中的句子

如何检测句点之间包含<span>标记的<p>标记中的句子
EN

Stack Overflow用户
提问于 2019-09-01 05:37:10
回答 4查看 71关注 0票数 1

我正在尝试检测/抓取

标记中包含< span >标记的句子。我想要得到一组句号之间的整个句子。这必须为整个网页做。

例如,下面的段落包含我想要提取的span句子:

代码语言:javascript
运行
复制
<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?

我在网上尝试过不同的正则表达式组合,但它们都不起作用。

EN

回答 4

Stack Overflow用户

发布于 2019-09-01 05:47:38

代码语言:javascript
运行
复制
   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>,并分别使用previousSiblingnextSibling访问它之前和之后的文本。要获得围绕它的“句子”,请使用。把句子分开。

到目前为止,这还没有完成,可能有前一个或下一个节点不是文本节点的情况,或者这些文本节点中没有点的情况。你必须适当地处理这些情况。

请参见:

Node on MDN

Text on MDN

.querySelectorAll on MDN

票数 3
EN

Stack Overflow用户

发布于 2019-09-01 05:42:47

您可以使用JavaScript。让我们将句子存储在一个数组中。

句子:

代码语言: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:

代码语言: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数组的结果:

代码语言:javascript
运行
复制
"The sun is shining today"
"It's a special day of celebration"
票数 2
EN

Stack Overflow用户

发布于 2019-09-01 06:12:47

使用split方法分隔句子,然后搜索有span的句子

代码语言:javascript
运行
复制
const p=document.getElementsByTagName('p')[0].innerHTML;
p.split(".").forEach(e=>{
  if(e.indexOf('span')>0){
    console.log(e);
  }
});
代码语言:javascript
运行
复制
<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> 

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57741743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档