-
下载包:
go get github.com/PuerkitoBio/goquery
-
示例代码:
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func ExampleScrape() {
// 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
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
// Find the review items
doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
// For each item found, get the band and title
band := s.Find("a").Text()
title := s.Find("i").Text()
fmt.Printf("Review %d: %s - %s\n", i, band, title)
})
}
func main() {
ExampleScrape()
}
你没看错,就是把https://github.com/PuerkitoBio/goquery的示例代码copy了过来,偷个懒
-
常用方法:
//返回标签的内容
selection.Find("span.lab-round").First().Text()
//返回标签内的html
selection.Find("span.lab-round").First().Html()
//返回标签内的属性
selection.Find("span.lab-round").First().Attr("href")
Find方法内选择器跟JQuery的一样,ID选择器、类选择器、标签选择器等等,参考JQuery或下面的页面链接
-
参考页面