-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauvieux-scraper.go
72 lines (58 loc) · 1.42 KB
/
auvieux-scraper.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
)
const searchURLBase = "http://www.auvieuxcampeur.fr/catalogsearch/result/?q="
func searchURL(id string) string {
return fmt.Sprintf("%s%s", searchURLBase, id)
}
type product struct {
ID string
Name string
Price float32
}
func convertPrice(pstr string) (float64, error) {
// Remove trailing ' €'
re := regexp.MustCompile(`^(\d+)€(\d+)?.*$`)
s := re.ReplaceAllString(strings.TrimSpace(pstr), "$1.$2")
return strconv.ParseFloat(s, 32)
}
func scrapeProduct(id string) (*product, error) {
url := searchURL(id)
doc, err := goquery.NewDocument(url)
if err != nil {
return nil, err
}
name := doc.Find("span.product-list-name").First().Text()
priceStr := doc.Find("span.price-content-container > span.orangeColor").First().Text()
price, err := convertPrice(priceStr)
if err != nil {
return nil, err
}
return &product{
ID: id,
Name: name,
Price: float32(price),
}, nil
}
func main() {
products := os.Args[1:]
if len(products) == 0 {
fmt.Println("Usage: auvieux-scraper product_id [product_id ...]")
os.Exit(1)
}
fmt.Printf("Référence;Désignation;Prix TTC\n")
for _, productID := range products {
p, err := scrapeProduct(productID)
if err != nil {
fmt.Printf("Error getting product %s (%s)\n", productID, err)
continue
}
fmt.Printf("%s;%s;%.2f\n", p.ID, p.Name, p.Price)
}
}