Best Rod code snippet using rod.ElementsByJS
query.go
Source:query.go
...187}188// Elements returns all elements that match the css selector189// è¿åå CSS éæ©å¨å¹é
çææå
ç´ 190func (p *Page) Elements(selector string) (Elements, error) {191 return p.ElementsByJS(evalHelper(js.Elements, selector))192}193// ElementsX returns all elements that match the XPath selector194// è¿åå XPath éæ©å¨å¹é
çææå
ç´ 195func (p *Page) ElementsX(xpath string) (Elements, error) {196 return p.ElementsByJS(evalHelper(js.ElementsX, xpath))197}198// ElementsByJS returns the elements from the return value of the js199// ElementsByJS ä» js çè¿åå¼ä¸è¿åå
ç´ ã200func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error) {201 res, err := p.Evaluate(opts.ByObject())202 if err != nil {203 return nil, err204 }205 if res.Subtype != proto.RuntimeRemoteObjectSubtypeArray {206 return nil, &ErrExpectElements{res}207 }208 defer func() { err = p.Release(res) }()209 list, err := proto.RuntimeGetProperties{210 ObjectID: res.ObjectID,211 OwnProperties: true,212 }.Call(p)213 if err != nil {214 return nil, err215 }216 elemList := Elements{}217 for _, obj := range list.Result {218 if obj.Name == "__proto__" || obj.Name == "length" {219 continue220 }221 val := obj.Value222 if val.Subtype != proto.RuntimeRemoteObjectSubtypeNode {223 return nil, &ErrExpectElements{val}224 }225 el, err := p.ElementFromObject(val)226 if err != nil {227 return nil, err228 }229 elemList = append(elemList, el)230 }231 return elemList, err232}233// Search for the given query in the DOM tree until the result count is not zero, before that it will keep retrying.234// å¨DOMæ ä¸æç´¢ç»å®çæ¥è¯¢ï¼ç´å°ç»æ计æ°ä¸ä¸ºé¶ï¼å¨æ¤ä¹åï¼å®å°ä¸æéè¯ã235// The query can be plain text or css selector or xpath.236// æ¥è¯¢å¯ä»¥æ¯çº¯ææ¬ãcsséæ©å¨æxpathã237// It will search nested iframes and shadow doms too.238// å®ä¹ä¼æç´¢åµå¥çiframesåå½±ådomã239func (p *Page) Search(query string) (*SearchResult, error) {240 sr := &SearchResult{241 page: p,242 restore: p.EnableDomain(proto.DOMEnable{}),243 }244 err := utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {245 if sr.DOMPerformSearchResult != nil {246 _ = proto.DOMDiscardSearchResults{SearchID: sr.SearchID}.Call(p)247 }248 res, err := proto.DOMPerformSearch{249 Query: query,250 IncludeUserAgentShadowDOM: true,251 }.Call(p)252 if err != nil {253 return true, err254 }255 sr.DOMPerformSearchResult = res256 if res.ResultCount == 0 {257 return false, nil258 }259 result, err := proto.DOMGetSearchResults{260 SearchID: res.SearchID,261 FromIndex: 0,262 ToIndex: 1,263 }.Call(p)264 if err != nil {265 // when the page is still loading the search result is not ready266 // å½é¡µé¢ä»ç¶å¨å è½½æ¶ï¼æ¤æ¶çæç´¢ç»æå°æªåå¤å¥½ã267 if errors.Is(err, cdp.ErrCtxNotFound) ||268 errors.Is(err, cdp.ErrSearchSessionNotFound) {269 return false, nil270 }271 return true, err272 }273 id := result.NodeIds[0]274 // TODO: This is definitely a bad design of cdp, hope they can optimize it in the future.275 // It's unnecessary to ask the user to explicitly call it.276 // 没æå¿
è¦è¦æ±ç¨æ·æç¡®å°è°ç¨å®ã277 //278 // When the id is zero, it means the proto.DOMDocumentUpdated has fired which will279 // invlidate all the existing NodeID. We have to call proto.DOMGetDocument280 // to reset the remote browser's tracker.281 // å½id为0æ¶ï¼æå³çproto.DOMDocumentUpdatedå·²ç»è§¦åï¼å®å°è°ç¨ææç°æçNodeIDã282 // æ们å¿
é¡»è°ç¨proto.DOMGetDocumentæ¥éç½®è¿ç¨æµè§å¨çè·è¸ªå¨ã283 if id == 0 {284 _, _ = proto.DOMGetDocument{}.Call(p)285 return false, nil286 }287 el, err := p.ElementFromNode(&proto.DOMNode{NodeID: id})288 if err != nil {289 return true, err290 }291 sr.First = el292 return true, nil293 })294 if err != nil {295 return nil, err296 }297 return sr, nil298}299// SearchResult handler300type SearchResult struct {301 *proto.DOMPerformSearchResult302 page *Page303 restore func()304 // First element in the search result305 // å¨æç´¢ç»æä¸ç第ä¸ä¸ªå
ç´ 306 First *Element307}308// Get l elements at the index of i from the remote search result.309// ä»è¿ç¨æç´¢ç»æä¸è·åç´¢å¼ä¸ºiçl个å
ç´ ã310func (s *SearchResult) Get(i, l int) (Elements, error) {311 result, err := proto.DOMGetSearchResults{312 SearchID: s.SearchID,313 FromIndex: i,314 ToIndex: i + l,315 }.Call(s.page)316 if err != nil {317 return nil, err318 }319 list := Elements{}320 for _, id := range result.NodeIds {321 el, err := s.page.ElementFromNode(&proto.DOMNode{NodeID: id})322 if err != nil {323 return nil, err324 }325 list = append(list, el)326 }327 return list, nil328}329// All returns all elements330// è¿åææå
ç´ 331func (s *SearchResult) All() (Elements, error) {332 return s.Get(0, s.ResultCount)333}334// Release the remote search result335// éæ¾æç´¢ç»æ336func (s *SearchResult) Release() {337 s.restore()338 _ = proto.DOMDiscardSearchResults{SearchID: s.SearchID}.Call(s.page)339}340type raceBranch struct {341 condition func(*Page) (*Element, error)342 callback func(*Element) error343}344// RaceContext stores the branches to race345// åå¨äº race çåæ¯346type RaceContext struct {347 page *Page348 branches []*raceBranch349}350// Race creates a context to race selectors351// 为 race éæ©å¨å建äºä¸ä¸ª RaceContext352func (p *Page) Race() *RaceContext {353 return &RaceContext{page: p}354}355// Element the doc is similar to MustElement356// ç±»ä¼¼äº MustElement357func (rc *RaceContext) Element(selector string) *RaceContext {358 rc.branches = append(rc.branches, &raceBranch{359 condition: func(p *Page) (*Element, error) { return p.Element(selector) },360 })361 return rc362}363// ElementFunc takes a custom function to determine race success364// ElementFunc éç¨èªå®ä¹å½æ°ç¡®å® race æå365func (rc *RaceContext) ElementFunc(fn func(*Page) (*Element, error)) *RaceContext {366 rc.branches = append(rc.branches, &raceBranch{367 condition: fn,368 })369 return rc370}371// ElementX the doc is similar to ElementX372// ç±»ä¼¼äº ElementX373func (rc *RaceContext) ElementX(selector string) *RaceContext {374 rc.branches = append(rc.branches, &raceBranch{375 condition: func(p *Page) (*Element, error) { return p.ElementX(selector) },376 })377 return rc378}379// ElementR the doc is similar to ElementR380//ç±»ä¼¼äº ElementR381func (rc *RaceContext) ElementR(selector, regex string) *RaceContext {382 rc.branches = append(rc.branches, &raceBranch{383 condition: func(p *Page) (*Element, error) { return p.ElementR(selector, regex) },384 })385 return rc386}387// ElementByJS the doc is similar to MustElementByJS388// ç±»ä¼¼äº MustELementByJS389func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext {390 rc.branches = append(rc.branches, &raceBranch{391 condition: func(p *Page) (*Element, error) { return p.ElementByJS(opts) },392 })393 return rc394}395// Handle adds a callback function to the most recent chained selector.396// Handle 为æè¿çé¾å¼éæ©å¨æ·»å ä¸ä¸ªåè°å½æ°ã397// The callback function is run, if the corresponding selector is398// present first, in the Race condition.399// å¦æç¸åºçéæ©å¨é¦å
åºç°å¨ trace æ¡ä»¶ä¸ï¼åè°å½æ°å°±ä¼è¿è¡ã400func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext {401 rc.branches[len(rc.branches)-1].callback = callback402 return rc403}404// Do the race405// æ§è¡ Trace406func (rc *RaceContext) Do() (*Element, error) {407 var el *Element408 err := utils.Retry(rc.page.ctx, rc.page.sleeper(), func() (stop bool, err error) {409 for _, branch := range rc.branches {410 bEl, err := branch.condition(rc.page.Sleeper(NotFoundSleeper))411 if err == nil {412 el = bEl.Sleeper(rc.page.sleeper)413 if branch.callback != nil {414 err = branch.callback(el)415 }416 return true, err417 } else if !errors.Is(err, &ErrElementNotFound{}) {418 return true, err419 }420 }421 return422 })423 return el, err424}425// Has an element that matches the css selector426// å¤ææ¯å¦æåCSSéæ©å¨ç¸å¹é
çå
ç´ 427func (el *Element) Has(selector string) (bool, *Element, error) {428 el, err := el.Element(selector)429 if errors.Is(err, &ErrElementNotFound{}) {430 return false, nil, nil431 }432 return err == nil, el, err433}434// HasX an element that matches the XPath selector435// å¤ææ¯å¦æåXPathç¸å¹é
çå
ç´ 436func (el *Element) HasX(selector string) (bool, *Element, error) {437 el, err := el.ElementX(selector)438 if errors.Is(err, &ErrElementNotFound{}) {439 return false, nil, nil440 }441 return err == nil, el, err442}443// HasR returns true if a child element that matches the css selector and its text matches the jsRegex.444// å¦ææä¸ä¸ªç¬¦åcsséæ©å¨çåå
ç´ ï¼å¹¶ä¸å
¶ææ¬ç¬¦åjsRegexï¼åHasRè¿åtrueã445func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error) {446 el, err := el.ElementR(selector, jsRegex)447 if errors.Is(err, &ErrElementNotFound{}) {448 return false, nil, nil449 }450 return err == nil, el, err451}452// Element returns the first child that matches the css selector453// è¿å第ä¸ä¸ªåCSSéæ©å¨å¹é
çåå
ç´ 454func (el *Element) Element(selector string) (*Element, error) {455 return el.ElementByJS(evalHelper(js.Element, selector))456}457// ElementR returns the first child element that matches the css selector and its text matches the jsRegex.458// ElementRè¿å符åcsséæ©å¨ç第ä¸ä¸ªåå
ç´ ï¼å¹¶ä¸å
¶ææ¬ç¬¦åjsRegexã459func (el *Element) ElementR(selector, jsRegex string) (*Element, error) {460 return el.ElementByJS(evalHelper(js.ElementR, selector, jsRegex))461}462// ElementX returns the first child that matches the XPath selector463// è¿å第ä¸ä¸ªå XPath éæ©å¨ç¸å¹é
çåå
ç´ 464func (el *Element) ElementX(xPath string) (*Element, error) {465 return el.ElementByJS(evalHelper(js.ElementX, xPath))466}467// ElementByJS returns the element from the return value of the js468// ElementByJS ä» js çè¿åå¼ä¸è¿å该å
ç´ ã469func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error) {470 e, err := el.page.Sleeper(NotFoundSleeper).ElementByJS(opts.This(el.Object))471 if err != nil {472 return nil, err473 }474 return e.Sleeper(el.sleeper), nil475}476// Parent returns the parent element in the DOM tree477// è¿å DOM æ ä¸çç¶å
ç´ ã478func (el *Element) Parent() (*Element, error) {479 return el.ElementByJS(Eval(`() => this.parentElement`))480}481// Parents that match the selector482// åéæ©å¨å¹é
çç¶å
ç´ ã483func (el *Element) Parents(selector string) (Elements, error) {484 return el.ElementsByJS(evalHelper(js.Parents, selector))485}486// Next returns the next sibling element in the DOM tree487// è¿åDOMæ ä¸çä¸ä¸ä¸ªå级å
ç´ 488func (el *Element) Next() (*Element, error) {489 return el.ElementByJS(Eval(`() => this.nextElementSibling`))490}491// Previous returns the previous sibling element in the DOM tree492// è¿åDOMæ ä¸çä¸ä¸ä¸ªå级å
ç´ 493func (el *Element) Previous() (*Element, error) {494 return el.ElementByJS(Eval(`() => this.previousElementSibling`))495}496// Elements returns all elements that match the css selector497// è¿åå CSS éæ©å¨ç¸å¹é
çææå
ç´ 498func (el *Element) Elements(selector string) (Elements, error) {499 return el.ElementsByJS(evalHelper(js.Elements, selector))500}501// ElementsX returns all elements that match the XPath selector502// è¿åå XPath éæ©å¨ç¸å¹é
çææå
ç´ 503func (el *Element) ElementsX(xpath string) (Elements, error) {504 return el.ElementsByJS(evalHelper(js.ElementsX, xpath))505}506// ElementsByJS returns the elements from the return value of the js507// ElementsByJS ä» js çè¿åå¼ä¸è¿åå
ç´ ã508func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error) {509 return el.page.Context(el.ctx).ElementsByJS(opts.This(el.Object))510}...
query_test.go
Source:query_test.go
...249 _, err := p.ElementByJS(rod.Eval(`1`))250 t.Is(err, &rod.ErrExpectElement{})251 t.Eq(err.Error(), "expect js to return an element, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")252}253func (t T) PageElementsByJS() {254 p := t.page.MustNavigate(t.srcFile("fixtures/selector.html")).MustWaitLoad()255 t.Len(p.MustElementsByJS("document.querySelectorAll('button')"), 4)256 _, err := p.ElementsByJS(rod.Eval(`[1]`))257 t.Is(err, &rod.ErrExpectElements{})258 t.Eq(err.Error(), "expect js to return an array of elements, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")259 _, err = p.ElementsByJS(rod.Eval(`1`))260 t.Eq(err.Error(), "expect js to return an array of elements, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")261 _, err = p.ElementsByJS(rod.Eval(`foo()`))262 t.Err(err)263 t.mc.stubErr(1, proto.RuntimeGetProperties{})264 _, err = p.ElementsByJS(rod.Eval(`[document.body]`))265 t.Err(err)266 t.mc.stubErr(4, proto.RuntimeCallFunctionOn{})267 t.Err(p.Elements("button"))268}269func (t T) PageElementTimeout() {270 page := t.page.MustNavigate(t.blank())271 start := time.Now()272 _, err := page.Timeout(300 * time.Millisecond).Element("not-exists")273 t.Is(err, context.DeadlineExceeded)274 t.Gte(time.Since(start), 300*time.Millisecond)275}276func (t T) PageElementMaxRetry() {277 page := t.page.MustNavigate(t.blank())278 s := func() utils.Sleeper { return utils.CountSleeper(5) }...
ElementsByJS
Using AI Code Generation
1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 page.MustWaitLoad()5 input := page.MustElement("input[name='q']")6 input.MustInput("rod")7 page.MustElement("input[name='btnK']").MustClick()8 page.MustWaitLoad()9 links := page.MustElementsByJS(`10 Array.from(document.querySelectorAll('h3')).map(el => el.innerText)11 for _, link := range links {12 println(link.MustText())13 }14}
ElementsByJS
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 page.MustElement("input[name=q]").MustInput("rod").MustPress(proto.InputKeyEventEnter)5 page.MustElementByJS(`[href="/search?q=rod&oq=rod"]`).MustClick()6 fmt.Println(page.MustInfo().URL)7}
ElementsByJS
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Headless(false)4 defer l.Cleanup()5 page.MustElement("#hplogo").MustWaitLoad()6 page.MustElement("#hplogo").MustScrollIntoView()7 page.MustElement("#hplogo").MustHover()8 page.MustElement("#hplogo").MustClick()9 page.MustElement("#hplogo").MustWaitStable()10 page.MustElement("#hplogo").MustWaitInvisible()11 page.MustElement("#hplogo").MustWaitVisible()12 page.MustElement("#hplogo").MustWaitReady()13 page.MustElement("#hplogo").MustWaitRequestIdle()14 page.MustElement("#hplogo").MustWaitNavigation()15 page.MustElement("#hplogo").MustWaitLoad()16 page.MustElement("#hplogo").MustWaitStable()17 page.MustElement("#hplogo").MustWaitInvisible()18 page.MustElement("#hplogo").MustWaitVisible()19 page.MustElement("#hplogo").MustWaitReady()20 page.MustElement("#hplogo").MustWaitRequestIdle()21 page.MustElement("#hplogo").MustWaitNavigation()22 page.MustElement("#hplogo").MustWaitLoad()23 page.MustElement("#hplogo").MustWaitStable()24 page.MustElement("#hplogo").MustWaitInvisible()25 page.MustElement("#hplogo").MustWaitVisible()26 page.MustElement("#hplogo").MustWaitReady()27 page.MustElement("#hplogo").MustWaitRequestIdle()28 page.MustElement("#hplogo").MustWaitNavigation()29 page.MustElement("#hplogo").MustWaitLoad()30 page.MustElement("#hplogo").MustWaitStable()31 page.MustElement("#hplogo").MustWaitInvisible()32 page.MustElement("#hplogo").MustWaitVisible()33 page.MustElement("#hplogo").MustWaitReady()34 page.MustElement("#hplogo").MustWaitRequestIdle()35 page.MustElement("#hplogo").MustWaitNavigation()36 page.MustElement("#hplogo").MustWaitLoad()37 page.MustElement("#hplogo").MustWaitStable()38 page.MustElement("#hplogo").MustWaitInvisible()39 page.MustElement("#hplogo").MustWaitVisible()40 page.MustElement("#hplogo").MustWaitReady()41 page.MustElement("#hplogo").MustWaitRequestIdle()42 page.MustElement("#hplogo").Must
ElementsByJS
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Headless(false)4 defer l.Cleanup()5 browser := rod.New().ControlURL(l).MustConnect()6 page := browser.MustPage("")7 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()8 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()9 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()10 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()11 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()12 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()13 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()14 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()15 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()16 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89b").MustClick()17 page.MustElement("#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input.gNO89
ElementsByJS
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Bin("/usr/bin/chromium-browser").Headless(false).MustLaunch()4 defer l.Close()5 page.MustElement("input").MustInput("rod").MustPress(input.Enter)6 page.MustElement("input").MustInput("rod").MustPress(input.Enter).MustElement("h3").MustClick()
ElementsByJS
Using AI Code Generation
1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 input := page.MustElementByJS(`document.querySelector("input")`)5 input.MustInput("rod")6 fmt.Println(input.MustProperty("value").String())7}8import (9func main() {10 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()11 input := page.MustElementByJS(`document.querySelector("input")`)12 input.MustInput("rod")13 fmt.Println(input.MustProperty("value").String())14}15import (16func main() {17 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()18 input := page.MustElementByJS(`document.querySelector("input")`)19 input.MustInput("rod")20 fmt.Println(input.MustProperty("value").String())21}22import (
ElementsByJS
Using AI Code Generation
1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 elements := page.MustElements(".example")5 for _, element := range elements {6 fmt.Println(element.MustText())7 }8}9page.ElementByXPath(xPath string)10import (11func main() {12 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()13 fmt.Println(element.MustText())14}15page.ElementsByXPath(xPath string)
ElementsByJS
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 defer browser.Close()5 page.ElementByJS(`document.querySelector("a[href='/gp/help/customer/display.html']").click()`)6 text := page.ElementByJS(`document.querySelector("h1.a-spacing-small").textContent`).Text()7 fmt.Println(text)8}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!