package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"sync"
)
const URL = "https://learnku.com/go?filter=created_at_1_month&order=score&l=y"
var wg sync.WaitGroup
func main() {
wg.Add(1)
go fetchArticles()
wg.Wait()
fmt.Println("完成抓取....")
}
func fetchArticles() {
defer wg.Done()
req, _ := http.NewRequest("GET", URL, nil)
resp, _ := http.DefaultClient.Do(req)
content, _ := ioutil.ReadAll(resp.Body)
respBody := string(content)
reg := regexp.MustCompile(`<span class="topic-title">(?s:(.*?))</span>`)
if reg == nil {
fmt.Println("regex err")
return
}
result := reg.FindAllStringSubmatch(respBody, -1)
for _, values := range result {
title := trimHtml(values[1])
fmt.Println(title)
}
}
func trimHtml(src string) string {
re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
src = re.ReplaceAllStringFunc(src, strings.ToLower)
re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
src = re.ReplaceAllString(src, "")
re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
src = re.ReplaceAllString(src, "")
re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
src = re.ReplaceAllString(src, "\n")
re, _ = regexp.Compile("\\s{2,}")
src = re.ReplaceAllString(src, "\n")
return strings.TrimSpace(src)
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結