試用 Golang 抓取網站價錢


1
2
3
export GOPATH=$(pwd)
go get github.com/PuerkitoBio/goquery
go run test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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"))
}