-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetURLs.go
More file actions
41 lines (33 loc) · 781 Bytes
/
getURLs.go
File metadata and controls
41 lines (33 loc) · 781 Bytes
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
package main
import (
"net/url"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func GetURLsFromHTML(htmlBody, rawBaseURL string) ([]string, error) {
htmlReader := strings.NewReader(htmlBody)
rootNode, err := html.Parse(htmlReader)
if err != nil {
return []string{}, err
}
urls := []string{}
baseUrl, err := url.Parse(rawBaseURL)
if err != nil {
return []string{}, err
}
for n := range rootNode.Descendants() {
if n.Type == html.ElementNode && n.DataAtom == atom.A {
for _, attr := range n.Attr {
if attr.Key == "href" {
parsedUrl, err := url.Parse(attr.Val)
if err != nil {
return []string{}, err
}
urls = append(urls, baseUrl.ResolveReference(parsedUrl).String())
}
}
}
}
return urls, nil
}