update examples to use the preferred NewDocumentFromReader approach

This commit is contained in:
Martin Angers
2018-03-24 12:12:09 -04:00
parent a86ea07301
commit dd77530fdb
2 changed files with 28 additions and 5 deletions

View File

@@ -95,15 +95,27 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"net/http"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
) )
func ExampleScrape() { func ExampleScrape() {
doc, err := goquery.NewDocument("http://metalsucks.net") // Request the HTML page.
if err != nil { res, err := http.Get("http://metalsucks.net")
log.Fatal(err) if err != nil {
} log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}
// Load the HTML document
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
// Find the review items // Find the review items
doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) { doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {

View File

@@ -3,14 +3,25 @@ package goquery_test
import ( import (
"fmt" "fmt"
"log" "log"
"net/http"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
) )
// This example scrapes the reviews shown on the home page of metalsucks.net. // This example scrapes the reviews shown on the home page of metalsucks.net.
func Example() { func Example() {
// Request the HTML page.
res, err := http.Get("http://metalsucks.net")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}
// Load the HTML document // Load the HTML document
doc, err := goquery.NewDocument("http://metalsucks.net") doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }