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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路