goquery是go语言中一个强大的html解析工具。解析方法类似于juqery.
代码
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func ExampleScrape() {
// Request the HTML page.
res, err := http.Get("https://zhangwenbing.com/sitemap.html")
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(".list-group-item").Each(func(i int, s *goquery.Selection) {
// For each item found, get the band and title
url, _ := s.Find("a").Attr("href")
fmt.Println(url)
})
}
func main() {
ExampleScrape()
}
这个是我在开通熊掌号时将我博客里面的所有文章链接爬出来,作为历史数据提交用的。使用起来非常简单。