你可以使用goquery来获取DOM的类型名称。

huangapple go评论82阅读模式
英文:

How can I get the type name of DOM using goquery?

问题

我想使用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) {
		// 调试用
		println(s.Size()) // 返回1

		// 我期望在这个URL上找到'<center>',但是我无法获取它的名称。
		// println(s.First().xxx) // ?
	})
}
英文:

I want to get the type name of DOM like 'a', img', 'tr', 'td', 'center' using goquery.
How can I get?

package main

import (
	&quot;github.com/PuerkitoBio/goquery&quot;
)

func main() {
	doc, _ := goquery.NewDocument(&quot;https://news.ycombinator.com/&quot;)
	doc.Find(&quot;html body&quot;).Each(func(_ int, s *goquery.Selection) {
        // for debug.
		println(s.Size()) // return 1

		// I expect &#39;&lt;center&gt;&#39; on this URL, but I can&#39;t get it&#39;s name.
        // println(s.First().xxx) // ?
	})
}

答案1

得分: 5

*Selection.First 给出了另一个包含 *html.Node 切片的 *Selection,其中 Data 字段包含:

> 元素节点的标签名称,文本内容

所以类似这样:

package main

import (
    "github.com/PuerkitoBio/goquery"
    "golang.org/x/net/html"
)

func main() {
    doc, _ := goquery.NewDocument("https://news.ycombinator.com/")
    doc.Find("html body").Each(func(_ int, s *goquery.Selection) {
        // for debug.
        println(s.Size()) // 返回 1

        if len(s.Nodes) > 0 && s.Nodes[0].Type == html.ElementNode {
            println(s.Nodes[0].Data)
        }
    })
}
英文:

*Selection.First gives you another *Selection which contains a slice of *html.Node which has a Data field which contains:

> tag name for element nodes, content for text

So something like that:

package main

import (
    &quot;github.com/PuerkitoBio/goquery&quot;
    &quot;golang.org/x/net/html&quot;
)

func main() {
    doc, _ := goquery.NewDocument(&quot;https://news.ycombinator.com/&quot;)
    doc.Find(&quot;html body&quot;).Each(func(_ int, s *goquery.Selection) {
        // for debug.
        println(s.Size()) // return 1

        if len(s.Nodes) &gt; 0 &amp;&amp; s.Nodes[0].Type == html.ElementNode {
            println(s.Nodes[0].Data)
        }
    })
}

huangapple
  • 本文由 发表于 2015年10月17日 14:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/33183508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定