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

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

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

问题

我想使用goquery获取DOM的类型名称,例如'a'、'img'、'tr'、'td'、'center'。我该如何获取?

  1. package main
  2. import (
  3. "github.com/PuerkitoBio/goquery"
  4. )
  5. func main() {
  6. doc, _ := goquery.NewDocument("https://news.ycombinator.com/")
  7. doc.Find("html body").Each(func(_ int, s *goquery.Selection) {
  8. // 调试用
  9. println(s.Size()) // 返回1
  10. // 我期望在这个URL上找到'<center>',但是我无法获取它的名称。
  11. // println(s.First().xxx) // ?
  12. })
  13. }
英文:

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

  1. package main
  2. import (
  3. &quot;github.com/PuerkitoBio/goquery&quot;
  4. )
  5. func main() {
  6. doc, _ := goquery.NewDocument(&quot;https://news.ycombinator.com/&quot;)
  7. doc.Find(&quot;html body&quot;).Each(func(_ int, s *goquery.Selection) {
  8. // for debug.
  9. println(s.Size()) // return 1
  10. // I expect &#39;&lt;center&gt;&#39; on this URL, but I can&#39;t get it&#39;s name.
  11. // println(s.First().xxx) // ?
  12. })
  13. }

答案1

得分: 5

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

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

所以类似这样:

  1. package main
  2. import (
  3. "github.com/PuerkitoBio/goquery"
  4. "golang.org/x/net/html"
  5. )
  6. func main() {
  7. doc, _ := goquery.NewDocument("https://news.ycombinator.com/")
  8. doc.Find("html body").Each(func(_ int, s *goquery.Selection) {
  9. // for debug.
  10. println(s.Size()) // 返回 1
  11. if len(s.Nodes) > 0 && s.Nodes[0].Type == html.ElementNode {
  12. println(s.Nodes[0].Data)
  13. }
  14. })
  15. }
英文:

*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:

  1. package main
  2. import (
  3. &quot;github.com/PuerkitoBio/goquery&quot;
  4. &quot;golang.org/x/net/html&quot;
  5. )
  6. func main() {
  7. doc, _ := goquery.NewDocument(&quot;https://news.ycombinator.com/&quot;)
  8. doc.Find(&quot;html body&quot;).Each(func(_ int, s *goquery.Selection) {
  9. // for debug.
  10. println(s.Size()) // return 1
  11. if len(s.Nodes) &gt; 0 &amp;&amp; s.Nodes[0].Type == html.ElementNode {
  12. println(s.Nodes[0].Data)
  13. }
  14. })
  15. }

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:

确定