1
0
mirror of https://github.com/MontFerret/ferret.git synced 2025-04-25 12:24:54 +02:00

103 lines
2.1 KiB
Go
Raw Normal View History

2018-09-26 22:03:06 -04:00
package static
2018-09-18 16:42:38 -04:00
import (
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
2018-09-18 16:42:38 -04:00
"github.com/PuerkitoBio/goquery"
)
type HTMLDocument struct {
2018-10-05 19:40:09 -04:00
*HTMLElement
url values.String
2018-09-18 16:42:38 -04:00
}
func NewHTMLDocument(
2018-09-18 16:42:38 -04:00
url string,
node *goquery.Document,
) (*HTMLDocument, error) {
2018-09-18 16:42:38 -04:00
if url == "" {
return nil, core.Error(core.ErrMissedArgument, "document url")
}
if node == nil {
return nil, core.Error(core.ErrMissedArgument, "document root selection")
}
2018-10-05 19:40:09 -04:00
el, err := NewHTMLElement(node.Selection)
2018-09-18 16:42:38 -04:00
if err != nil {
return nil, err
}
return &HTMLDocument{el, values.NewString(url)}, nil
2018-09-18 16:42:38 -04:00
}
func (doc *HTMLDocument) Type() core.Type {
return core.HTMLDocumentType
2018-09-18 16:42:38 -04:00
}
func (doc *HTMLDocument) Compare(other core.Value) int {
2018-09-18 16:42:38 -04:00
switch other.Type() {
case core.HTMLDocumentType:
otherDoc := other.(values.HTMLDocument)
return doc.url.Compare(otherDoc.URL())
2018-09-18 16:42:38 -04:00
default:
if other.Type() > core.HTMLDocumentType {
2018-09-18 16:42:38 -04:00
return -1
}
return 1
}
}
func (doc *HTMLDocument) URL() core.Value {
return doc.url
}
func (doc *HTMLDocument) InnerHTMLBySelector(selector values.String) values.String {
selection := doc.selection.Find(selector.String())
str, err := selection.Html()
// TODO: log error
if err != nil {
return values.EmptyString
}
return values.NewString(str)
}
func (doc *HTMLDocument) InnerHTMLBySelectorAll(selector values.String) *values.Array {
selection := doc.selection.Find(selector.String())
arr := values.NewArray(selection.Length())
selection.Each(func(_ int, selection *goquery.Selection) {
str, err := selection.Html()
// TODO: log error
if err == nil {
arr.Push(values.NewString(str))
}
})
return arr
}
func (doc *HTMLDocument) InnerTextBySelector(selector values.String) values.String {
selection := doc.selection.Find(selector.String())
return values.NewString(selection.Text())
}
func (doc *HTMLDocument) InnerTextBySelectorAll(selector values.String) *values.Array {
selection := doc.selection.Find(selector.String())
arr := values.NewArray(selection.Length())
selection.Each(func(_ int, selection *goquery.Selection) {
arr.Push(values.NewString(selection.Text()))
})
return arr
}