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

Function Example

example_test.go:15–44  ·  view source on GitHub ↗

This example scrapes the reviews shown on the home page of metalsucks.net.

()

Source from the content-addressed store, hash-verified

13
14// This example scrapes the reviews shown on the home page of metalsucks.net.
15func Example() {
16 // Request the HTML page.
17 res, err := http.Get("http://metalsucks.net")
18 if err != nil {
19 log.Fatal(err)
20 }
21 defer res.Body.Close()
22 if res.StatusCode != 200 {
23 log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
24 }
25
26 // Load the HTML document
27 doc, err := goquery.NewDocumentFromReader(res.Body)
28 if err != nil {
29 log.Fatal(err)
30 }
31
32 // Find the review items
33 doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
34 // For each item found, get the band and title
35 band := s.Find("a").Text()
36 title := s.Find("i").Text()
37 fmt.Printf("Review %d: %s - %s\n", i, band, title)
38 })
39 // To see the output of the Example while running the test suite (go test), simply
40 // remove the leading "x" before Output on the next line. This will cause the
41 // example to fail (all the "real" tests should pass).
42
43 // xOutput: voluntarily fail the Example output.
44}
45
46// This example shows how to use NewDocumentFromReader from a file.
47func ExampleNewDocumentFromReader_file() {

Callers

nothing calls this directly

Calls 5

NewDocumentFromReaderFunction · 0.92
GetMethod · 0.80
EachMethod · 0.80
FindMethod · 0.80
TextMethod · 0.80

Tested by

no test coverage detected