dsgw3315 2018-02-04 17:48
浏览 39


I want to get contents of html.Node as a string.


<div id="my-node">
  <p>First paragraph</p>
  <p>Second paragraph</p>

Given myNode := html.Node("#my-node") (pseudocode), I want to retrieve entire above html as a string. Indentation does not matter.

I couldn't find anything on the internet except iterating over contents of node - myNode.NextSibling but its over complicated and I'm pretty sure there has to be easier way.

Update: I'm reffering to golang.org/x/net/html package.

  • 写回答

1条回答 默认 最新

  • du9757 2018-02-05 17:14

    I get what you mean, I use a lot of this in tests.

    What you need is already in the same x/net/html package - you can Render the Node to a bytes.Buffer then get a string out of it:

    var b bytes.Buffer
    err := html.Render(&b, node)
    return b.String()

    Please read the doc how rendering is done on the best effort basis - but it will probably fit you.

    PS. You can consult how it's used in a more real project of mine: https://github.com/wkhere/htmlx/blob/master/finder.go#L32-L39 https://github.com/wkhere/htmlx/blob/master/finder_test.go#L73

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流