Add Atributes All feature

This commit is contained in:
kotamat 2017-09-18 15:20:25 +09:00 committed by Kenneth Shaw
parent 8f3b889b9f
commit 07208b1cc3
2 changed files with 74 additions and 4 deletions

View File

@ -209,6 +209,35 @@ func Attributes(sel interface{}, attributes *map[string]string, opts ...QueryOpt
}, opts...) }, opts...)
} }
// AttributesAll retrieves the element attributes for every nodes matching the
// selector.
// selector should be ByQueryAll
func AttributesAll(sel interface{}, attributes *[]map[string]string, opts ...QueryOption) Action {
if attributes == nil {
panic("attributes cannot be nil")
}
return QueryAfter(sel, func(ctxt context.Context, h cdp.Handler, nodes ...*cdp.Node) error {
if len(nodes) < 1 {
return fmt.Errorf("selector `%s` did not return any nodes", sel)
}
for _, node := range nodes {
node.RLock()
defer node.RUnlock()
m := make(map[string]string)
attrs := node.Attributes
for i := 0; i < len(attrs); i += 2 {
m[attrs[i]] = attrs[i+1]
}
*attributes = append(*attributes, m)
}
return nil
}, opts...)
}
// SetAttributes sets the element attributes for the first node matching the // SetAttributes sets the element attributes for the first node matching the
// selector. // selector.
func SetAttributes(sel interface{}, attributes map[string]string, opts ...QueryOption) Action { func SetAttributes(sel interface{}, attributes map[string]string, opts ...QueryOption) Action {

View File

@ -399,6 +399,47 @@ func TestAttributes(t *testing.T) {
} }
} }
func TestAttributesAll(t *testing.T) {
t.Parallel()
c := testAllocate(t, "image.html")
defer c.Release()
tests := []struct {
sel string
by QueryOption
exp []map[string]string
}{
{"img", ByQueryAll,
[]map[string]string{
{
"alt": "Brankas - Easy Money Management",
"id": "icon-brankas",
"src": "images/brankas.png",
},
{
"alt": "How people build software",
"id": "icon-github",
"src": "images/github.png",
},
},
},
}
var err error
for i, test := range tests {
var attrs []map[string]string
err = c.Run(defaultContext, AttributesAll(test.sel, &attrs, test.by))
if err != nil {
t.Fatalf("test %d got error: %v", i, err)
}
if !reflect.DeepEqual(test.exp, attrs) {
t.Errorf("test %d expected %v, got: %v", i, test.exp, attrs)
}
}
}
func TestSetAttributes(t *testing.T) { func TestSetAttributes(t *testing.T) {
tests := []struct { tests := []struct {
sel string sel string