...

Source file src/golang.org/x/net/html/example_test.go

Documentation: golang.org/x/net/html

     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  
     5  //go:build go1.23
     6  
     7  // This example demonstrates parsing HTML data and walking the resulting tree.
     8  package html_test
     9  
    10  import (
    11  	"fmt"
    12  	"log"
    13  	"strings"
    14  
    15  	"golang.org/x/net/html"
    16  	"golang.org/x/net/html/atom"
    17  )
    18  
    19  func ExampleParse() {
    20  	s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
    21  	doc, err := html.Parse(strings.NewReader(s))
    22  	if err != nil {
    23  		log.Fatal(err)
    24  	}
    25  	for n := range doc.Descendants() {
    26  		if n.Type == html.ElementNode && n.DataAtom == atom.A {
    27  			for _, a := range n.Attr {
    28  				if a.Key == "href" {
    29  					fmt.Println(a.Val)
    30  					break
    31  				}
    32  			}
    33  		}
    34  	}
    35  
    36  	// Output:
    37  	// foo
    38  	// /bar/baz
    39  }
    40  

View as plain text