golang爬虫之goquery
时间:2018-08-07 02:15:05 +0800 CST 浏览:564

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()
}

这个是我在开通熊掌号时将我博客里面的所有文章链接爬出来,作为历史数据提交用的。使用起来非常简单。



如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧