Golang福利爬蟲

大囚長發表於2018-08-02

沒事的時候跑兩把,窮人專用。

package main

import (
    "bytes"
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "log"
    "math"
    "net/http"
    "runtime"
    "strconv"
    "strings"
    "sync"
    "time"
)

func Scraper(page string, now int64) string {
    // Request the HTML page.
    ScrapeURL := "https://51.ruyo.net/page/" + page
    client := &http.Client{}
    reqest, _ := http.NewRequest("GET", ScrapeURL, nil)
    reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
    //reqest.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
    reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
    reqest.Header.Set("Cache-Control", "max-age=0")
    reqest.Header.Set("Connection", "keep-alive")
    reqest.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36")
    res, err := client.Do(reqest)
    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
    var buffer bytes.Buffer
    buffer.WriteString("**********Scraped page " + page + "**********\n")
    doc.Find(".panel-body .entry-header").Each(func(i int, s *goquery.Selection) {
        // For each item found, get the band and title
        title := s.Find("h3").ChildrenFiltered("a").Text()
        url, _ := s.Find("h3").ChildrenFiltered("a").Attr("href")
        etime, _ := s.Find("div").ChildrenFiltered("time").Attr("datetime")
        etime = strings.Replace(etime, "+00:00", "", -1) + "Z"
        dt, _ := time.Parse(time.RFC3339, etime)
        intdt := dt.Unix()
        difftime := math.Abs(float64(now - intdt))
        //fmt.Println(now, intdt, difftime)
        if difftime <= 2592000 {
            buffer.WriteString("Review " + strconv.Itoa(i) + ": " + title + "\n" + url + "\n" + etime + "\n")
        }
    })
    return buffer.String()
}

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    now := time.Now().Unix()
    ch := make(chan string, 5)
    wg := &sync.WaitGroup{}
    var page string
    for i := 1; i < 6; i++ {
        wg.Add(1)
        go func(i int) {
            page = strconv.Itoa(i)
            fmt.Printf("Scraping page %s...\n", page)
            ch <- Scraper(page, now)
            wg.Done()
        }(i)
    }
    wg.Wait()

    //print result
    for i := 0; i < 6; i++ {
        fmt.Println(<-ch)
    }
}

相關文章