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.
()
| 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. |
| 115 | func 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 | } |
nothing calls this directly
no test coverage detected