猿问

如何使用 goquery 获取 DOM 的类型名称?

我想使用 goquery 获取 DOM 的类型名称,如“a”、“img”、“tr”、“td”、“center”。我怎样才能得到?


package main


import (

    "github.com/PuerkitoBio/goquery"

)


func main() {

    doc, _ := goquery.NewDocument("https://news.ycombinator.com/")

    doc.Find("html body").Each(func(_ int, s *goquery.Selection) {

        // for debug.

        println(s.Size()) // return 1


        // I expect '<center>' on this URL, but I can't get it's name.

        // println(s.First().xxx) // ?

    })

}


慕侠2389804
浏览 183回答 1
1回答

慕姐8265434

*Selection.First给你另一个*Selection包含一片*html.Node具有Data其中包含字段:元素节点的标签名称,文本的内容所以像这样:package mainimport (&nbsp; &nbsp; "github.com/PuerkitoBio/goquery"&nbsp; &nbsp; "golang.org/x/net/html")func main() {&nbsp; &nbsp; doc, _ := goquery.NewDocument("https://news.ycombinator.com/")&nbsp; &nbsp; doc.Find("html body").Each(func(_ int, s *goquery.Selection) {&nbsp; &nbsp; &nbsp; &nbsp; // for debug.&nbsp; &nbsp; &nbsp; &nbsp; println(s.Size()) // return 1&nbsp; &nbsp; &nbsp; &nbsp; if len(s.Nodes) > 0 && s.Nodes[0].Type == html.ElementNode {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; println(s.Nodes[0].Data)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}
随时随地看视频慕课网APP

相关分类

Go
我要回答