-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_urls_from_html.go
44 lines (40 loc) · 1008 Bytes
/
get_urls_from_html.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
package main
import (
"strings"
"fmt"
"golang.org/x/net/html"
"net/url"
)
func getURLsFromHTML(htmlBody, rawBaseURL string) ([]string, error){
reader := strings.NewReader(htmlBody)
doc, err := html.Parse(reader)
if err != nil {
return []string{}, fmt.Errorf("GO 13, Error %w", err)
}
var absoluteURLs []string
var f func(*html.Node)
f = func(n *html.Node){
if n.Type == html.ElementNode && n.Data == "a"{
for _, a := range n.Attr {
if a.Key == "href" {
parsedURL, err := url.Parse(a.Val)
if err != nil {
fmt.Errorf("Error parsing URL: %w", err)
break
}
if parsedURL.Scheme == ""{
absoluteURLs = append(absoluteURLs, rawBaseURL + parsedURL.Path)
}else{
absoluteURLs = append(absoluteURLs,a.Val)
}
break
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
return absoluteURLs, nil
}