package main
import (
"golang.org/x/net/html"
"fmt"
"os"
"io"
"net/http"
)
func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
if pre != nil {
pre(n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
forEachNode(c, pre, post)
}
if post != nil {
post(n)
}
}
var depth int
func startElement(n *html.Node) {
if n.Type == html.ElementNode {
fmt.Printf("%*s\n", depth*2, "", n.Data)
depth++
}
}
func endElement(n *html.Node) {
if n.Type == html.ElementNode {
depth--
fmt.Printf("%*s%s>\n", depth*2, "", n.Data)
}
}
func main() {
fmt.Printf("%*s \n", 20, ""); // %*s输出20个空格
htmlByte := fetch2("http://36.7.130.14:8080/affairs/Article.asp?id=2430")
doc, err := html.Parse(htmlByte)
if err != nil{
fmt.Fprintf(os.Stderr, "fetch error: %v \n", err)
os.Exit(1)
}
forEachNode(doc, startElement, endElement)
}
func fetch2(url string) io.ReadCloser {
resp, err := http.Get(url)
if err != nil{
fmt.Fprintf(os.Stderr, "fetch error: %v \n", err)
os.Exit(1)
}
//b, err := ioutil.ReadAll(resp.Body)
//resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "reading error: %s , %v \n", url, err )
os.Exit(1)
}
// fmt.Printf("fectch reslt : %s", string(b))
return resp.Body
}
---------------------------------------------------------------------------------
输出:
...............