程序开发 · 2024年12月29日

如何获取标签的内部 HTML 或文本?

当前位置: > > > > 如何获取标签的内部 HTML 或文本?

来源:stackoverflow
2024-04-20 19:48:34
0浏览
收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何获取标签的内部 HTML 或文本?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我们如何根据下面的示例获取锚文本的值?这是我的代码。我可以使用 html.elementnode 获取 hreftitle 的值。我需要仅使用 golang.org/x/net/html 来获取文本的值,而不使用其他库。

示例:从 <a href="https:xyz.com">text xyz</a> 中,我想获取“text xyz”。

// html.ElementNode works for getting href and title value but no text value with TextNode. 
if n.Type == html.TextNode && n.Data == "a" {
    for _, a := range n.Attr {
        if a.Key == "href" {
            text = a.Val
        }
    }
}

正确答案

给定 html:

<a href="http://example.com/1">go to <b>example</b> 1</a>
<p>some para text</p>
<a href="http://example.com/2">go to <b>example</b> 2</a>

您只希望看到文字吗?

go to example 1
go to example 2

您期望内部 html 吗?

go to <b>example</b>example 1
go to <b>example</b>example 2

或者,你还期待别的吗?

以下程序仅提供文本或内部 html。每次找到锚节点时,它都会保存该节点,然后继续沿着该节点的树向下移动。当它遇到其他节点时,它会检查已保存的节点,并附加 textnodes 的文本或将节点的 html 呈现到缓冲区。最后,在遍历所有子节点并重新遇到保存的锚节点后,它会打印文本字符串和 html 缓冲区,重置两个变量,然后将锚节点清零。

我想到了使用缓冲区和 html.render,并保存来自 的特定节点。

以下内容也在 中:

package main

import (
    "bytes"
    "fmt"
    "io"
    "strings"

    "golang.org/x/net/html"
)

func main() {
    s := `
    <a href="http://example.com/1">go to <b>example</b> 1</a>
    <p>some para text</p>
    <a href="http://example.com/2">go to <b>example</b> 2</a>
    `

    doc, _ := html.parse(strings.newreader(s))

    var nanchor *html.node
    var stxt string
    var bufinnerhtml bytes.buffer

    w := io.writer(&bufinnerhtml)

    var f func(*html.node)
    f = func(n *html.node) {
        if n.type == html.elementnode && n.data == "a" {
            nanchor = n
        }

        if nanchor != nil {
            if n != nanchor { // don't write the a tag and its attributes
                html.render(w, n)
            }
            if n.type == html.textnode {
                stxt += n.data
            }
        }

        for c := n.firstchild; c != nil; c = c.nextsibling {
            f(c)
        }

        if n == nanchor {
            fmt.println("text:", stxt)
            fmt.println("innerhtml:", bufinnerhtml.string())
            stxt = ""
            bufinnerhtml.reset()
            nanchor = nil
        }
    }
    f(doc)
}
Text: Go to example 1
InnerHTML: Go to <b>example</b>example 1
Text: Go to example 2
InnerHTML: Go to <b>example</b>example 2

以上就是《如何获取标签的内部 HTML 或文本?》的详细内容,更多关于的资料请关注公众号!