亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲取標簽的內部 HTML 或只是文本?

如何獲取標簽的內部 HTML 或只是文本?

Go
繁花不似錦 2023-02-21 16:03:50
我們如何根據下面的示例獲取錨文本的值?這是我的代碼。href我可以獲得和title使用的價值html.ElementNode。我需要僅使用 text 來獲取文本的值golang.org/x/net/html,而無需使用其他庫。示例:從<a href="https:xyz.com">Text XYZ</a>,我想獲得“文本 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        }    }}
查看完整描述

1 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

給定 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,并保存特定節點,從Golang 解析 HTML,提取帶有標簽的所有內容。


以下內容也在Playground中:


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


查看完整回答
反對 回復 2023-02-21
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號