How to use ElementsByJS method of rod Package

Best Rod code snippet using rod.ElementsByJS

query.go

Source:query.go Github

copy

Full Screen

...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}...

Full Screen

Full Screen

query_test.go

Source:query_test.go Github

copy

Full Screen

...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) }...

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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()

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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 (

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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)

Full Screen

Full Screen

ElementsByJS

Using AI Code Generation

copy

Full Screen

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}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Rod automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful