試用 Golang 抓取網站價錢

export GOPATH=$(pwd)  
go get github.com/PuerkitoBio/goquery  
go run test.go

package main
 
 import (
     "fmt"
     "github.com/PuerkitoBio/goquery"
     "strings"
     "regexp"
     "time"
 )
 
 const (
     TARGET_URL = "http://www.example.com/goods/show/99"
 )
 
 func main() {
     var document *goquery.Document
     var e error
    
     if document, e = goquery.NewDocument(TARGET_URL); e != nil {
         panic(e.Error())
     }
    
     name  := strings.TrimSpace(document.Find("table.jmb tr").Eq(2).Find("td span").First().Text())
     price := strings.TrimSpace(document.Find("table.jmb tr").Eq(2).Find("td span").Last().Text())
    
     matches := regexp.MustCompile(`(\d+).*=.* (\d+).*=.*`).FindAllStringSubmatch(price, -1)[0]
 
     price1b  := matches[1]
     price10b := matches[2]
    
     fmt.Printf(
         "%-30s %-30s %-30s %-20d %-30s\n", name, price1b, price10b,
         time.Now().Unix(), time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05"))
 }
- See more at: http://www.actkr.com/?p=1299#sthash.YZStcb4C.xtGqd6Hh.dpuf

你可能感兴趣的:(試用 Golang 抓取網站價錢)