You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
834 B

  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // This example demonstrates parsing HTML data and walking the resulting tree.
  5. package html_test
  6. import (
  7. "fmt"
  8. "log"
  9. "strings"
  10. "golang.org/x/net/html"
  11. )
  12. func ExampleParse() {
  13. s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
  14. doc, err := html.Parse(strings.NewReader(s))
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. var f func(*html.Node)
  19. f = func(n *html.Node) {
  20. if n.Type == html.ElementNode && n.Data == "a" {
  21. for _, a := range n.Attr {
  22. if a.Key == "href" {
  23. fmt.Println(a.Val)
  24. break
  25. }
  26. }
  27. }
  28. for c := n.FirstChild; c != nil; c = c.NextSibling {
  29. f(c)
  30. }
  31. }
  32. f(doc)
  33. // Output:
  34. // foo
  35. // /bar/baz
  36. }