You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

html_helper.go 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package integrations
  5. import (
  6. "bytes"
  7. "golang.org/x/net/html"
  8. )
  9. type HtmlDoc struct {
  10. doc *html.Node
  11. body *html.Node
  12. }
  13. func NewHtmlParser(content []byte) (*HtmlDoc, error) {
  14. doc, err := html.Parse(bytes.NewReader(content))
  15. if err != nil {
  16. return nil, err
  17. }
  18. return &HtmlDoc{doc: doc}, nil
  19. }
  20. func (doc *HtmlDoc) GetBody() *html.Node {
  21. if doc.body == nil {
  22. var b *html.Node
  23. var f func(*html.Node)
  24. f = func(n *html.Node) {
  25. if n.Type == html.ElementNode && n.Data == "body" {
  26. b = n
  27. return
  28. }
  29. for c := n.FirstChild; c != nil; c = c.NextSibling {
  30. f(c)
  31. }
  32. }
  33. f(doc.doc)
  34. if b != nil {
  35. doc.body = b
  36. } else {
  37. doc.body = doc.doc
  38. }
  39. }
  40. return doc.body
  41. }
  42. func (doc *HtmlDoc) GetAttribute(n *html.Node, key string) (string, bool) {
  43. for _, attr := range n.Attr {
  44. if attr.Key == key {
  45. return attr.Val, true
  46. }
  47. }
  48. return "", false
  49. }
  50. func (doc *HtmlDoc) checkAttr(n *html.Node, attr, val string) bool {
  51. if n.Type == html.ElementNode {
  52. s, ok := doc.GetAttribute(n, attr)
  53. if ok && s == val {
  54. return true
  55. }
  56. }
  57. return false
  58. }
  59. func (doc *HtmlDoc) traverse(n *html.Node, attr, val string) *html.Node {
  60. if doc.checkAttr(n, attr, val) {
  61. return n
  62. }
  63. for c := n.FirstChild; c != nil; c = c.NextSibling {
  64. result := doc.traverse(c, attr, val)
  65. if result != nil {
  66. return result
  67. }
  68. }
  69. return nil
  70. }
  71. func (doc *HtmlDoc) GetElementById(id string) *html.Node {
  72. return doc.traverse(doc.GetBody(), "id", id)
  73. }
  74. func (doc *HtmlDoc) GetInputValueById(id string) string {
  75. inp := doc.GetElementById(id)
  76. if inp == nil {
  77. return ""
  78. }
  79. val, _ := doc.GetAttribute(inp, "value")
  80. return val
  81. }
  82. func (doc *HtmlDoc) GetElementByName(name string) *html.Node {
  83. return doc.traverse(doc.GetBody(), "name", name)
  84. }
  85. func (doc *HtmlDoc) GetInputValueByName(name string) string {
  86. inp := doc.GetElementByName(name)
  87. if inp == nil {
  88. return ""
  89. }
  90. val, _ := doc.GetAttribute(inp, "value")
  91. return val
  92. }