登录
首页 >  Golang >  Go问答

使用 ReplaceWithSelection 在 goquery 中替换 html 元素无效

来源:stackoverflow

时间:2024-02-16 21:42:25 107浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《使用 ReplaceWithSelection 在 goquery 中替换 html 元素无效》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

✌️

我正在尝试使用“github.com/puerkitobio/goquery”将 html 父元素替换为其子元素。但是,replacewithselection 不会替换任何内容,选择内容保持不变。

package main

import (
    "os"
    "strings"

    "github.com/PuerkitoBio/goquery"
)

var html = `
<section>
    <article>
        <h2>Article 1</h2>
        <p>Text for article #1</p>
    </article>
    <article>
        <h2>Article 2</h2>
        <p>Text for article #2</p>
    </article>
</section>
`

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

    section := qHtml.Find(`section`)
    sectionChildren := section.Children().Clone()
    section.ReplaceWithSelection(sectionChildren)

    goquery.Render(os.Stdout, section)
}

正确答案


由于 section 仅引用我们正在使用 ReplaceWithSelection 的实际 document 中的子项之一,因此更改将反映在实际文档中,而不是参考中,该参考可能已从实际 document 替换,但由于您仍然拥有参考,因此您仍可以查看以实际变化为准。

要查看更改而不是使用 section,请使用已完成更改的 document

改变

goquery.render(os.stdout, section)

goquery.Render(os.Stdout, qHtml.Contents())

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>