我正在尝试在goquery
的帮助下解析这个html。我不知道如何解析字符串“我需要的字符串”,同时扔掉其他所有内容。
<div class="outter-class">
<h1 class="inner-class">
The string I need
<span class="other-class" >Some value I don't need</span>
<span class="other-class2" title="sometitle"></span>
</h1>
<div class="other-class3">
<h3>Some heading i don't need</h3>
</div>
</div>
我尝试使用类似:https://stackoverflow.com/a/8851526/989919通过将其调整为像这样的 goquery:
test := s.Clone().Children().Empty().End().Text()
fmt.Println(test.Text())
但这行不通。我尝试了 API 中的许多不同变体但我无法弄清楚。
最佳答案
我让它工作的方式是:
// End() lets us jump back to the h1 selection to get its text
text := doc.Find("h1").Children().Remove().End().Text()
text = strings.TrimSpace(text)
fmt.Println(text)
输出:
The string I need
代码从 h1 元素中删除子节点(span 元素)以获得正确的输出。可能有一种更简单的方法可以做到这一点,但它确实有效。 :)
关于jquery - 从没有子元素的 div 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32635943/