-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathparser.go
64 lines (52 loc) · 1.36 KB
/
parser.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
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
)
type Article struct {
Title string
Link string
Comments int
CommentsLink string
}
func parseArticles(htmlContent string) ([]Article, error) {
var articles []Article
doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
if err != nil {
return nil, err
}
doc.Find("tr.athing").Each(func(i int, s *goquery.Selection) {
title := s.Find("td.title > span.titleline > a").Text()
link, _ := s.Find("td.title > span.titleline > a").Attr("href")
commentText := s.Next().Find("a[href^='item']").Last().Text()
commentsCount, err := extractCommentsCountFromString(commentText)
commentsLink := s.Next().Find("a[href^='item']").Last().AttrOr("href", "")
if err != nil {
commentsCount = 0
}
article := Article{
Title: title,
Link: link,
Comments: commentsCount,
CommentsLink: commentsLink,
}
articles = append(articles, article)
})
return articles, nil
}
func extractCommentsCountFromString(input string) (int, error) {
input = strings.TrimSpace(input)
re := regexp.MustCompile(`\d+`)
matches := re.FindString(input)
if matches == "" {
return 0, fmt.Errorf("no numbers found in input")
}
number, err := strconv.Atoi(matches)
if err != nil {
return 0, err
}
return number, nil
}