gpt4 book ai didi

go - 使用 GoQuery 在换行符上拆分元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:11 27 4
gpt4 key购买 nike

我正在尝试使用 GoQuery 从页面获取内容,但由于某些原因我无法在换行符处进行拆分 (br)。

HTML,看起来像这样:

<ul>
<li>I'm skipped</li>

<li>
Text Into - <p>Whatever</p>
<p>
Line 1<br />
Line 2<br />
Line 3<br />
Line 4<br />
Line N
</p>
</li>
</ul>

去代码:

doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
panic(err)
}

doc.Find("ul").Each(func(i int, s *goquery.Selection) {

str := s.Find("li p").Next().Text()

fmt.Println(str, "--")

})

出于某种原因,我无法将每一行都以 p 标记中的分隔符分隔为单个项目。上面代码的输出是:

Line1Line2Line3Line4LineN--

但我要实现的输出应该是这样的:

Line1--
Line2--
Line3--
Line4--
LineN--

由于我是 Go 新手,请在评论中让我知道如果有什么不清楚的,所以我会尽可能多地解释它。

谢谢。

最佳答案

.Text() 将:

Text gets the combined text contents of each element in the set of matched elements, including their descendants.

所以您真正想要做的是获取内容并过滤掉任何 br 标签。正如戴夫的回答所说,那里有换行符,所以我也修剪了那些:

package main

import (
"fmt"
"github.com/PuerkitoBio/goquery"
"strings"
)

var input string = `
<ul>
<li>I'm skipped</li>

<li>
Text Into - <p>Whatever</p>
<p>
Line 1<br />
Line 2<br />
Line 3<br />
Line 4<br />
Line N
</p>
</li>
</ul>
`

func main() {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(input))
if err != nil {
panic(err)
}

doc.Find("ul").Each(func(i int, s *goquery.Selection) {

p := s.Find("li p").Next()
p.Contents().Each(func(i int, s *goquery.Selection) {
if !s.Is("br") {
fmt.Println(strings.TrimSpace(s.Text()), "--")
}

})

})
}

产生:

Line 1 --
Line 2 --
Line 3 --
Line 4 --
Line N --

关于go - 使用 GoQuery 在换行符上拆分元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239543/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com