【问题标题】:Selecting text only following certain elements using javascript/jquery使用 javascript/jquery 仅在某些元素之后选择文本
【发布时间】:2013-02-15 12:23:58
【问题描述】:

如下面的 sn-p 所示,我有多个文本 div,其中有一个粗体部分,然后是一个换行符,然后是一段文本。我可以找到()粗体部分,但我怎样才能使用 javascript/jquery 仅获取粗体部分之后的换行符之后的文本部分?

<div class="thecontent">
any amount of text or html elements before
<b>
    the bolded text
</b>
<br>
the text I need together with the bolded text which can contain other html
elements apart from line breaks and bolded blocks
<br>
<b>
    posibility of more bolded and text couples further in the div
</b>
<br>
and some more text to go with the bolded text
</div>

在一个 div 中可以有多个粗体部分和文本对,并且需要的文本片段以换行符结尾、另一个粗体部分或 div 的结尾。文本块中可能还有其他html元素,如&lt;a href&gt;

我可以使用.find('b') 获取&lt;b&gt; &lt;/b&gt; 的内容,并且我尝试使用nodeType == 3 来选择文本节点,但这只能获取所有文本。

很遗憾,我无法更改页面的 html。有没有人有解决方案?在此先感谢:)

根据要求,输入将以粗体形式阻止换行符和后面的文本。我需要文本跟随它们直到换行或另一个粗体部分。

输出将是一个变量中的粗体文本以及换行符之后但直到另一个变量中的下一个换行符或粗体元素的文本。

所以 html 示例的输出是:the bolded text + the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks

posibility of more bolded and text couples further in the div + and some more text to go with the bolded text

【问题讨论】:

  • 我无法理解您的问题,您想要获得粗体(在&lt;b&gt; &lt;/b&gt;内)但仍在div.thecontent内的文本内容?跨度>
  • 我的目标是将粗体部分与其后面的文本配对(直到下一个换行符或下一个粗体部分)
  • 你为什么不把你的div分成更小的容器(比如&lt;div&gt;&lt;span&gt;),每个容器都包含你想要过滤的连贯文本部分?
  • @Joe 你能让你的问题简单易懂吗?
  • @Joe,你能创建一个简单的实际输入和预期输出示例吗?

标签: javascript jquery html web-scraping


【解决方案1】:

我不认为有一种非常简单的方法可以获取所有节点并将它们分开等,但它确实是可能的。由于我不知道您打算对文本做什么,所以我制作了一个简洁的小对象,其中包含应该更容易使用的所有内容,或者您​​可以更改代码以满足您的需求:

var elem    = $('.thecontent').get(0).childNodes,
    content = {},
    i = 0;

for (key in elem) {
    var type = elem[key].tagName ? elem[key].tagName : 'text';
    content[i] = {};
    content[i][type] = elem[key].tagName == 'B' ? $(elem[key]).text() : elem[key].nodeValue;
    i++;
}

console.log( content );

FIDDLE

这会返回:

{"0": {"text" : "any amount of text or html elements before"},
 "1": {"B"    : "the bolded text"},
 "2": {"text" : "\n"}, //also returns newlines
 "3": {"BR"   : null},
 "4": {"text" : "the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks"},
 "5": {"BR"   : null},
 "6": {"text" : "\n"},
 "7": {"B"    : " posibility of more bolded and text couples further in the div"},
 "8": {"text" : "\n"},
 "9": {"BR"   : null},
 "10":{"text" : "and some more text to go with the bolded text"},
}

您可以根据行号(从零开始)、标记名、文本内容或您需要的任何其他内容进行过滤?

【讨论】:

  • 谢谢!这是一个很大的帮助,我可以遍历数组。
  • 不客气。它应该更容易使用,因为您至少可以从行号或标记名中选择每段文本,并且代码显示了如何获取它们,因此如果您不需要对象,您也可以更改它,但宁愿立即对返回的文本做一些事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
相关资源
最近更新 更多