MCPcopy Create free account
hub / github.com/PuerkitoBio/goquery / ExampleText

Function ExampleText

example_test.go:115–148  ·  view source on GitHub ↗

This example shows how to use the goquery.Text function to extract clean, human-readable text from a selection, similar to BeautifulSoup's get_text.

()

Source from the content-addressed store, hash-verified

113// This example shows how to use the goquery.Text function to extract clean,
114// human-readable text from a selection, similar to BeautifulSoup's get_text.
115func ExampleText() {
116 page := `
117<html>
118 <body>
119 <div id="content">
120 <h1> Hello </h1>
121 <p>world</p>
122 <script>var ignored = 1;</script>
123 </div>
124 </body>
125</html>
126`
127 doc, err := goquery.NewDocumentFromReader(strings.NewReader(page))
128 if err != nil {
129 log.Fatal(err)
130 }
131
132 // Trim each text node, join the remaining ones with a space, and skip the
133 // text of <script> and <style> elements.
134 text := goquery.Text(doc.Find("#content"), &goquery.TextOptions{
135 Separator: " ",
136 Trim: true,
137 Keep: func(n *html.Node) bool {
138 if p := n.Parent; p != nil && p.Type == html.ElementNode {
139 return p.Data != "script" && p.Data != "style"
140 }
141 return true
142 },
143 })
144 fmt.Println(text)
145
146 // Output:
147 // Hello world
148}

Callers

nothing calls this directly

Calls 3

NewDocumentFromReaderFunction · 0.92
TextFunction · 0.92
FindMethod · 0.80

Tested by

no test coverage detected