如何在使用html包的golang中打印css选择器之间的文本?

huangapple go评论119阅读模式
英文:

How to print text between css selectors in golang using html package?

问题

我有一个HTML文档:

  1. <value>1,2,3</value>
  2. <value>,1,3,5</value>

我想使用下面的代码提取文本,但它只打印出'value'标签(CSS选择器)。如何使用Golang的html包打印标签之间的文本而不是标签本身?

  1. z := html.NewTokenizer(b)
  2. for {
  3. tt := z.Next()
  4. switch {
  5. case tt == html.ErrorToken:
  6. return
  7. case tt == html.StartTagToken:
  8. t := z.Token()
  9. isAnchor := t.Data == "value"
  10. if isAnchor {
  11. fmt.Println(t.Data)
  12. }
  13. }
  14. }
英文:

I have html document

  1. <value>1,2,3</value>
  2. <value>,1,3,5</value>

and what to extract text with code below but it only prints 'value' tags (css selectors). How to print the text from between tags instead using golang html package ?

  1. z := html.NewTokenizer(b)
  2. for {
  3. tt := z.Next()
  4. switch {
  5. case tt == html.ErrorToken:
  6. return
  7. case tt == html.StartTagToken:
  8. t := z.Token()
  9. isAnchor := t.Data == "value"
  10. if isAnchor {
  11. fmt.Println(t.Data)
  12. }
  13. }
  14. }

答案1

得分: 4

这对我来说似乎有效:

  1. r := strings.NewReader("<value>1,2,3</value><value>,1,3,5</value>")
  2. doc, err := html.Parse(r)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. var f func(*html.Node)
  7. f = func(n *html.Node) {
  8. if n.Type == html.ElementNode && n.Data == "value" {
  9. fmt.Println(n.FirstChild.Data)
  10. }
  11. for c := n.FirstChild; c != nil; c = c.NextSibling {
  12. f(c)
  13. }
  14. }
  15. f(doc)

我认为关键是在找到"value"节点后获取FirstChild。

英文:

This seems to work for me:

  1. r := strings.NewReader(&quot;&lt;value&gt;1,2,3&lt;/value&gt;&lt;value&gt;,1,3,5&lt;/value&gt;&quot;)
  2. doc, err := html.Parse(r)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. var f func(*html.Node)
  7. f = func(n *html.Node) {
  8. if n.Type == html.ElementNode &amp;&amp; n.Data == &quot;value&quot; {
  9. fmt.Println(n.FirstChild.Data)
  10. }
  11. for c := n.FirstChild; c != nil; c = c.NextSibling {
  12. f(c)
  13. }
  14. }
  15. f(doc)

I think the key is grabbing the FirstChild after finding the "value" node.

答案2

得分: 1

你必须在下一个Token上使用Text()方法。

  1. 如果isAnchor := t.Data == "value"; isAnchor {
  2. z.Next()
  3. fmt.Println(z.Text())
  4. }
英文:

You have to use Text() method on the next Token.

  1. if isAnchor := t.Data == &quot;value&quot;; isAnchor {
  2. z.Next()
  3. fmt.Println(z.Text())
  4. }

huangapple
  • 本文由 发表于 2016年11月22日 21:27:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/40743101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定