doumo0206 2014-10-02 00:28
浏览 207
已采纳

使用goQuery按ID搜索标签

I would like to retrieve all the tags with a specific id using Go. Apparently the easiest way to do that is go is to use goquery.

Assume I am looking for ul tags with id MyTag in a website site. I would like to list all the li contained in such a ul. I never used jQuery before so I feel a little lost.

resp, _ := http.Get(site)
httpBody := resp.Body
node, _ := html.Parse(httpBody)
document := goquery.NewDocumentFromNode(node)
document.Find("ul.MyTag").Each(func(i int, ul *goquery.Selection) { //MyTag will not work here
    ul.Find("li").Each(func (i int, li *goquery.Selection){
        ...
   })
})

More specitically, my html looks like

<html>
    <body>
        <ui id="yes">
            <li key="1">a</li>
            <li key="2">b</li>
            <li key="3">c</li>
            <li key="4">d</li>
        </ui>

        <ui id="no">
            <li key="1">11</li>
            <li key="2">22</li>
            <li key="3">33</li>
            <li key="4">44</li>
        </ui>
    </body>
</html>

and I would like to retreive the keys 1,2,3,4

Bonus question: why Each has an int argument? It doesn't seem to be used at all

  • 写回答

1条回答 默认 最新

  • dqzve68846 2014-10-02 00:56
    关注

    GoQuery uses the same selector syntax as jQuery/CSS. To that end, if you want to find an element with a specific ID .. then you need to use a hash # symbol.

    document.Find("ul#MyTag")...
    

    That being said, ID's are supposed to be unique. The above code you're using (that I provided in a previous question of yours) .. searches by class (the dot . notation).

    Show us the markup you're using this on and I will be able to see exactly where you're going wrong.

    RE: Your bonus question. The int argument is the index of the element within its parent. You don't have to use it.. it is provided by goquery though.

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

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)