dq1230123 2017-02-09 16:47
浏览 64
已采纳

GoLang-GoQuery HTML插入失败

I wish to extract elementB, and then stop before element C and D - i.e., do not extract the .text of content elementC and elementD. However, I only know how to extract the entire div text, using Contents().Not to ignore elementC, but elementD is still captured.

Here is the code I am currently using:

GoLang:

capturedText := s.Find("div").Contents().Not(".label").Text()

Which ignores elementC, but not elementD, which has no outer tags.

HTML:

<li><span><h2>elementA</h2></span><div>elementB<br><span class="label">elementC</span>elementD</div></li>

How do I capture only elementB of <div>, and not elementC and elementD?

Edit:

I have tried closing the div tag like so:

s.Find(".label").BeforeHtml(`</div>`)

and also tried:

s.Find(".label").BeforeHtml(`</div><div>`)

and accessing the first div, disregarding the second div which should now have elementD with:

jp, _ := s.Find("div").First().Html()

However, this is not working. It seems that </div> must not be an open tag - it needs to be <div>...</div> to insert correctly. But this is NOT what I need, I require ONLY </div> or </div><div> to close the first div correctly.

What is the appropriate way to fix this?

  • 写回答

1条回答 默认 最新

  • duanou8504 2017-02-10 20:36
    关注

    Since I can't edit the HTML with a 'broken' node, I have opted for this:

        s.Find(".label").BeforeHtml(`|_SEPARATOR_|`) // Insert text separator into Html
        preCleanNode := s.Find("div").Contents().Not(".label").Text() //Get Html as Text
        cleanNode := strings.Split(preCleanNode, `|_SEPARATOR_|`) // Split text based on Text Separator
        outputString := cleanNode[0] // Output our wanted text
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致