github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/find_frames.go (about)

     1  package html
     2  
     3  import (
     4  	"context"
     5  	"regexp"
     6  
     7  	"github.com/MontFerret/ferret/pkg/drivers"
     8  	"github.com/MontFerret/ferret/pkg/runtime/core"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values"
    10  )
    11  
    12  // FRAMES finds HTML frames by a given property selector.
    13  // Returns an empty array if frames not found.
    14  // @param {HTMLPage} page - HTML page.
    15  // @param {String} property - Property selector.
    16  // @param {String} exp - Regular expression to match property value.
    17  // @return {HTMLDocument[]} - Returns an array of found HTML frames.
    18  func Frames(ctx context.Context, args ...core.Value) (core.Value, error) {
    19  	err := core.ValidateArgs(args, 3, 3)
    20  
    21  	if err != nil {
    22  		return values.None, err
    23  	}
    24  
    25  	page, err := drivers.ToPage(args[0])
    26  
    27  	if err != nil {
    28  		return values.None, err
    29  	}
    30  
    31  	frames, err := page.GetFrames(ctx)
    32  
    33  	if err != nil {
    34  		return values.None, err
    35  	}
    36  
    37  	propName := values.ToString(args[1])
    38  	matcher, err := regexp.Compile(values.ToString(args[2]).String())
    39  
    40  	if err != nil {
    41  		return values.None, err
    42  	}
    43  
    44  	result, _ := frames.Find(func(value core.Value, idx int) bool {
    45  		doc, e := drivers.ToDocument(value)
    46  
    47  		if e != nil {
    48  			err = e
    49  			return false
    50  		}
    51  
    52  		currentPropValue, e := doc.GetIn(ctx, []core.Value{propName})
    53  
    54  		if e != nil {
    55  			err = e
    56  
    57  			return false
    58  		}
    59  
    60  		return matcher.MatchString(currentPropValue.String())
    61  	})
    62  
    63  	return result, err
    64  }