Skip to content

Instantly share code, notes, and snippets.

@maciekmm
Created August 8, 2015 09:19
Show Gist options
  • Save maciekmm/4de73211c7f88df3bed9 to your computer and use it in GitHub Desktop.
Save maciekmm/4de73211c7f88df3bed9 to your computer and use it in GitHub Desktop.
Extracts from values by parsing html page
func extractFormValues(reader io.Reader, names []string) (map[string]string, error) {
result := make(map[string]string, len(names))
doc, err := html.Parse(reader)
if err != nil {
return nil, err
}
var rec func(*html.Node)
rec = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "input" {
var name, value string
for _, v := range n.Attr {
if v.Key == "value" {
value = v.Val
}
if v.Key == "name" {
name = v.Val
}
}
num := 0
for _, nv := range names {
if name == nv {
result[name] = value
}
_, ok := result[name]
if ok {
num++
}
}
if num == len(names) {
return
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
rec(c)
}
}
rec(doc)
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment