vendor/github.com/go-rod/rod/query.go
543 lines · 14661 bytes
1// This file contains all query related code for Page and Element to separate the concerns.
2
3package rod
4
5import (
6 "errors"
7 "regexp"
8
9 "github.com/go-rod/rod/lib/cdp"
10 "github.com/go-rod/rod/lib/js"
11 "github.com/go-rod/rod/lib/proto"
12 "github.com/go-rod/rod/lib/utils"
13)
14
15// SelectorType enum.
16type SelectorType string
17
18const (
19 // SelectorTypeRegex type.
20 SelectorTypeRegex SelectorType = "regex"
21 // SelectorTypeCSSSector type.
22 SelectorTypeCSSSector SelectorType = "css-selector"
23 // SelectorTypeText type.
24 SelectorTypeText SelectorType = "text"
25)
26
27// Elements provides some helpers to deal with element list.
28type Elements []*Element
29
30// First returns the first element, if the list is empty returns nil.
31func (els Elements) First() *Element {
32 if els.Empty() {
33 return nil
34 }
35 return els[0]
36}
37
38// Last returns the last element, if the list is empty returns nil.
39func (els Elements) Last() *Element {
40 if els.Empty() {
41 return nil
42 }
43 return els[len(els)-1]
44}
45
46// Empty returns true if the list is empty.
47func (els Elements) Empty() bool {
48 return len(els) == 0
49}
50
51// Pages provides some helpers to deal with page list.
52type Pages []*Page
53
54// First returns the first page, if the list is empty returns nil.
55func (ps Pages) First() *Page {
56 if ps.Empty() {
57 return nil
58 }
59 return ps[0]
60}
61
62// Last returns the last page, if the list is empty returns nil.
63func (ps Pages) Last() *Page {
64 if ps.Empty() {
65 return nil
66 }
67 return ps[len(ps)-1]
68}
69
70// Empty returns true if the list is empty.
71func (ps Pages) Empty() bool {
72 return len(ps) == 0
73}
74
75// Find the page that has the specified element with the css selector.
76func (ps Pages) Find(selector string) (*Page, error) {
77 for _, page := range ps {
78 has, _, err := page.Has(selector)
79 if err != nil {
80 return nil, err
81 }
82 if has {
83 return page, nil
84 }
85 }
86 return nil, &PageNotFoundError{}
87}
88
89// FindByURL returns the page that has the url that matches the jsRegex.
90func (ps Pages) FindByURL(jsRegex string) (*Page, error) {
91 for _, page := range ps {
92 res, err := page.Eval(`() => location.href`)
93 if err != nil {
94 return nil, err
95 }
96 url := res.Value.String()
97 if regexp.MustCompile(jsRegex).MatchString(url) {
98 return page, nil
99 }
100 }
101 return nil, &PageNotFoundError{}
102}
103
104// Has an element that matches the css selector.
105func (p *Page) Has(selector string) (bool, *Element, error) {
106 el, err := p.Sleeper(NotFoundSleeper).Element(selector)
107 if errors.Is(err, &ElementNotFoundError{}) {
108 return false, nil, nil
109 }
110 if err != nil {
111 return false, nil, err
112 }
113 return true, el.Sleeper(p.sleeper), nil
114}
115
116// HasX an element that matches the XPath selector.
117func (p *Page) HasX(selector string) (bool, *Element, error) {
118 el, err := p.Sleeper(NotFoundSleeper).ElementX(selector)
119 if errors.Is(err, &ElementNotFoundError{}) {
120 return false, nil, nil
121 }
122 if err != nil {
123 return false, nil, err
124 }
125 return true, el.Sleeper(p.sleeper), nil
126}
127
128// HasR an element that matches the css selector and its display text matches the jsRegex.
129func (p *Page) HasR(selector, jsRegex string) (bool, *Element, error) {
130 el, err := p.Sleeper(NotFoundSleeper).ElementR(selector, jsRegex)
131 if errors.Is(err, &ElementNotFoundError{}) {
132 return false, nil, nil
133 }
134 if err != nil {
135 return false, nil, err
136 }
137 return true, el.Sleeper(p.sleeper), nil
138}
139
140// Element retries until an element in the page that matches the CSS selector, then returns
141// the matched element.
142func (p *Page) Element(selector string) (*Element, error) {
143 return p.ElementByJS(evalHelper(js.Element, selector))
144}
145
146// ElementR retries until an element in the page that matches the css selector and it's text matches the jsRegex,
147// then returns the matched element.
148func (p *Page) ElementR(selector, jsRegex string) (*Element, error) {
149 return p.ElementByJS(evalHelper(js.ElementR, selector, jsRegex))
150}
151
152// ElementX retries until an element in the page that matches one of the XPath selectors, then returns
153// the matched element.
154func (p *Page) ElementX(xPath string) (*Element, error) {
155 return p.ElementByJS(evalHelper(js.ElementX, xPath))
156}
157
158// ElementByJS returns the element from the return value of the js function.
159// If sleeper is nil, no retry will be performed.
160// By default, it will retry until the js function doesn't return null.
161// To customize the retry logic, check the examples of Page.Sleeper.
162func (p *Page) ElementByJS(opts *EvalOptions) (*Element, error) {
163 var res *proto.RuntimeRemoteObject
164 var err error
165
166 removeTrace := func() {}
167 err = utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {
168 remove := p.tryTraceQuery(opts)
169 removeTrace()
170 removeTrace = remove
171
172 res, err = p.Evaluate(opts.ByObject())
173 if err != nil {
174 return true, err
175 }
176
177 if res.Type == proto.RuntimeRemoteObjectTypeObject && res.Subtype == proto.RuntimeRemoteObjectSubtypeNull {
178 return false, nil
179 }
180
181 return true, nil
182 })
183 removeTrace()
184 if err != nil {
185 return nil, err
186 }
187
188 if res.Subtype != proto.RuntimeRemoteObjectSubtypeNode {
189 return nil, &ExpectElementError{res}
190 }
191
192 return p.ElementFromObject(res)
193}
194
195// Elements returns all elements that match the css selector.
196func (p *Page) Elements(selector string) (Elements, error) {
197 return p.ElementsByJS(evalHelper(js.Elements, selector))
198}
199
200// ElementsX returns all elements that match the XPath selector.
201func (p *Page) ElementsX(xpath string) (Elements, error) {
202 return p.ElementsByJS(evalHelper(js.ElementsX, xpath))
203}
204
205// ElementsByJS returns the elements from the return value of the js.
206func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error) {
207 res, err := p.Evaluate(opts.ByObject())
208 if err != nil {
209 return nil, err
210 }
211
212 if res.Subtype != proto.RuntimeRemoteObjectSubtypeArray {
213 return nil, &ExpectElementsError{res}
214 }
215
216 defer func() { err = p.Release(res) }()
217
218 list, err := proto.RuntimeGetProperties{
219 ObjectID: res.ObjectID,
220 OwnProperties: true,
221 }.Call(p)
222 if err != nil {
223 return nil, err
224 }
225
226 elemList := Elements{}
227 for _, obj := range list.Result {
228 if obj.Name == "__proto__" || obj.Name == "length" {
229 continue
230 }
231 val := obj.Value
232
233 if val.Subtype != proto.RuntimeRemoteObjectSubtypeNode {
234 return nil, &ExpectElementsError{val}
235 }
236
237 el, err := p.ElementFromObject(val)
238 if err != nil {
239 return nil, err
240 }
241
242 elemList = append(elemList, el)
243 }
244
245 return elemList, err
246}
247
248// Search for the given query in the DOM tree until the result count is not zero, before that it will keep retrying.
249// The query can be plain text or css selector or xpath.
250// It will search nested iframes and shadow doms too.
251func (p *Page) Search(query string) (*SearchResult, error) {
252 sr := &SearchResult{
253 page: p,
254 restore: p.EnableDomain(proto.DOMEnable{}),
255 }
256
257 err := utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {
258 if sr.DOMPerformSearchResult != nil {
259 _ = proto.DOMDiscardSearchResults{SearchID: sr.SearchID}.Call(p)
260 }
261
262 res, err := proto.DOMPerformSearch{
263 Query: query,
264 IncludeUserAgentShadowDOM: true,
265 }.Call(p)
266 if err != nil {
267 return true, err
268 }
269
270 sr.DOMPerformSearchResult = res
271
272 if res.ResultCount == 0 {
273 return false, nil
274 }
275
276 result, err := proto.DOMGetSearchResults{
277 SearchID: res.SearchID,
278 FromIndex: 0,
279 ToIndex: 1,
280 }.Call(p)
281 if err != nil {
282 // when the page is still loading the search result is not ready
283 if errors.Is(err, cdp.ErrCtxNotFound) ||
284 errors.Is(err, cdp.ErrSearchSessionNotFound) {
285 return false, nil
286 }
287 return true, err
288 }
289
290 id := result.NodeIDs[0]
291
292 // TODO: This is definitely a bad design of cdp, hope they can optimize it in the future.
293 // It's unnecessary to ask the user to explicitly call it.
294 //
295 // When the id is zero, it means the proto.DOMDocumentUpdated has fired which will
296 // invalidate all the existing NodeID. We have to call proto.DOMGetDocument
297 // to reset the remote browser's tracker.
298 if id == 0 {
299 _, _ = proto.DOMGetDocument{}.Call(p)
300 return false, nil
301 }
302
303 el, err := p.ElementFromNode(&proto.DOMNode{NodeID: id})
304 if err != nil {
305 return true, err
306 }
307
308 sr.First = el
309
310 return true, nil
311 })
312 if err != nil {
313 return nil, err
314 }
315
316 return sr, nil
317}
318
319// SearchResult handler.
320type SearchResult struct {
321 *proto.DOMPerformSearchResult
322
323 page *Page
324 restore func()
325
326 // First element in the search result
327 First *Element
328}
329
330// Get l elements at the index of i from the remote search result.
331func (s *SearchResult) Get(i, l int) (Elements, error) {
332 result, err := proto.DOMGetSearchResults{
333 SearchID: s.SearchID,
334 FromIndex: i,
335 ToIndex: i + l,
336 }.Call(s.page)
337 if err != nil {
338 return nil, err
339 }
340
341 list := Elements{}
342
343 for _, id := range result.NodeIDs {
344 el, err := s.page.ElementFromNode(&proto.DOMNode{NodeID: id})
345 if err != nil {
346 return nil, err
347 }
348 list = append(list, el)
349 }
350
351 return list, nil
352}
353
354// All returns all elements.
355func (s *SearchResult) All() (Elements, error) {
356 return s.Get(0, s.ResultCount)
357}
358
359// Release the remote search result.
360func (s *SearchResult) Release() {
361 s.restore()
362 _ = proto.DOMDiscardSearchResults{SearchID: s.SearchID}.Call(s.page)
363}
364
365type raceBranch struct {
366 condition func(*Page) (*Element, error)
367 callback func(*Element) error
368}
369
370// RaceContext stores the branches to race.
371type RaceContext struct {
372 page *Page
373 branches []*raceBranch
374}
375
376// Race creates a context to race selectors.
377func (p *Page) Race() *RaceContext {
378 return &RaceContext{page: p}
379}
380
381// ElementFunc takes a custom function to determine race success.
382func (rc *RaceContext) ElementFunc(fn func(*Page) (*Element, error)) *RaceContext {
383 rc.branches = append(rc.branches, &raceBranch{
384 condition: fn,
385 })
386 return rc
387}
388
389// Element is similar to [Page.Element].
390func (rc *RaceContext) Element(selector string) *RaceContext {
391 return rc.ElementFunc(func(p *Page) (*Element, error) {
392 return p.Element(selector)
393 })
394}
395
396// ElementX is similar to [Page.ElementX].
397func (rc *RaceContext) ElementX(selector string) *RaceContext {
398 return rc.ElementFunc(func(p *Page) (*Element, error) {
399 return p.ElementX(selector)
400 })
401}
402
403// ElementR is similar to [Page.ElementR].
404func (rc *RaceContext) ElementR(selector, regex string) *RaceContext {
405 return rc.ElementFunc(func(p *Page) (*Element, error) {
406 return p.ElementR(selector, regex)
407 })
408}
409
410// ElementByJS is similar to [Page.ElementByJS].
411func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext {
412 return rc.ElementFunc(func(p *Page) (*Element, error) {
413 return p.ElementByJS(opts)
414 })
415}
416
417// Search is similar to [Page.Search].
418func (rc *RaceContext) Search(query string) *RaceContext {
419 return rc.ElementFunc(func(p *Page) (*Element, error) {
420 res, err := p.Search(query)
421 if err != nil {
422 return nil, err
423 }
424 res.Release()
425 return res.First, nil
426 })
427}
428
429// Handle adds a callback function to the most recent chained selector.
430// The callback function is run, if the corresponding selector is
431// present first, in the Race condition.
432func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext {
433 rc.branches[len(rc.branches)-1].callback = callback
434 return rc
435}
436
437// Do the race.
438func (rc *RaceContext) Do() (*Element, error) {
439 var el *Element
440 err := utils.Retry(rc.page.ctx, rc.page.sleeper(), func() (stop bool, err error) {
441 for _, branch := range rc.branches {
442 bEl, err := branch.condition(rc.page.Sleeper(NotFoundSleeper))
443 if err == nil {
444 el = bEl.Sleeper(rc.page.sleeper)
445
446 if branch.callback != nil {
447 err = branch.callback(el)
448 }
449 return true, err
450 } else if !errors.Is(err, &ElementNotFoundError{}) {
451 return true, err
452 }
453 }
454 return
455 })
456 return el, err
457}
458
459// Has an element that matches the css selector.
460func (el *Element) Has(selector string) (bool, *Element, error) {
461 el, err := el.Element(selector)
462 if errors.Is(err, &ElementNotFoundError{}) {
463 return false, nil, nil
464 }
465 return err == nil, el, err
466}
467
468// HasX an element that matches the XPath selector.
469func (el *Element) HasX(selector string) (bool, *Element, error) {
470 el, err := el.ElementX(selector)
471 if errors.Is(err, &ElementNotFoundError{}) {
472 return false, nil, nil
473 }
474 return err == nil, el, err
475}
476
477// HasR returns true if a child element that matches the css selector and its text matches the jsRegex.
478func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error) {
479 el, err := el.ElementR(selector, jsRegex)
480 if errors.Is(err, &ElementNotFoundError{}) {
481 return false, nil, nil
482 }
483 return err == nil, el, err
484}
485
486// Element returns the first child that matches the css selector.
487func (el *Element) Element(selector string) (*Element, error) {
488 return el.ElementByJS(evalHelper(js.Element, selector))
489}
490
491// ElementR returns the first child element that matches the css selector and its text matches the jsRegex.
492func (el *Element) ElementR(selector, jsRegex string) (*Element, error) {
493 return el.ElementByJS(evalHelper(js.ElementR, selector, jsRegex))
494}
495
496// ElementX returns the first child that matches the XPath selector.
497func (el *Element) ElementX(xPath string) (*Element, error) {
498 return el.ElementByJS(evalHelper(js.ElementX, xPath))
499}
500
501// ElementByJS returns the element from the return value of the js.
502func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error) {
503 e, err := el.page.Context(el.ctx).Sleeper(NotFoundSleeper).ElementByJS(opts.This(el.Object))
504 if err != nil {
505 return nil, err
506 }
507 return e.Sleeper(el.sleeper), nil
508}
509
510// Parent returns the parent element in the DOM tree.
511func (el *Element) Parent() (*Element, error) {
512 return el.ElementByJS(Eval(`() => this.parentElement`))
513}
514
515// Parents that match the selector.
516func (el *Element) Parents(selector string) (Elements, error) {
517 return el.ElementsByJS(evalHelper(js.Parents, selector))
518}
519
520// Next returns the next sibling element in the DOM tree.
521func (el *Element) Next() (*Element, error) {
522 return el.ElementByJS(Eval(`() => this.nextElementSibling`))
523}
524
525// Previous returns the previous sibling element in the DOM tree.
526func (el *Element) Previous() (*Element, error) {
527 return el.ElementByJS(Eval(`() => this.previousElementSibling`))
528}
529
530// Elements returns all elements that match the css selector.
531func (el *Element) Elements(selector string) (Elements, error) {
532 return el.ElementsByJS(evalHelper(js.Elements, selector))
533}
534
535// ElementsX returns all elements that match the XPath selector.
536func (el *Element) ElementsX(xpath string) (Elements, error) {
537 return el.ElementsByJS(evalHelper(js.ElementsX, xpath))
538}
539
540// ElementsByJS returns the elements from the return value of the js.
541func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error) {
542 return el.page.Context(el.ctx).ElementsByJS(opts.This(el.Object))
543}