2

goquery - Iterate over All DOM Elements in HTML

 3 years ago
source link: http://siongui.github.io/2016/05/21/goquery-iterate-all-nodes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Iterate over all DOM nodes/elements via goquery in Golang (Go programming language).

The trick is to use Find("*") to access all nodes in DOM tree.

Install goquery Package

$ go get -u github.com/PuerkitoBio/goquery

Source Code

node.go | repository | view raw

package main

import (
	"github.com/PuerkitoBio/goquery"
	"strings"
)

const html = `<html>
  <head>
    <title>traverse</title>
  </head>
  <body>
    <div>
      Hello
      <span>World</span>
      <!-- Goquery -->
    </div>
  </body>
</html>`

func main() {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		panic(err)
	}

	doc.Find("*").Each(func(_ int, node *goquery.Selection) {
		println(node.Text())
	})
}

Tested on: Ubuntu Linux 16.04, Go 1.6.2.


References:

[1]github.com/PuerkitoBio/goquery - GoDoc

[2][Golang] Iterate over All DOM Elements in HTML


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK