How to use Example method of rod_test Package

Best Rod code snippet using rod_test.Example

examples_test.go

Source:examples_test.go Github

copy

Full Screen

...16 "github.com/go-rod/rod/lib/utils"17)18// This example opens https://github.com/, searches for "git",19// and then gets the header element which gives the description for Git.20func Example() {21 // Launch a new browser with default options, and connect to it.22 browser := rod.New().MustConnect()23 // Even you forget to close, rod will close it after main process ends.24 defer browser.MustClose()25 // Create a new page26 page := browser.MustPage("https://github.com")27 // We use css selector to get the search input element and input "git"28 page.MustElement("input").MustInput("git").MustPress(input.Enter)29 // Wait until css selector get the element then get the text content of it.30 text := page.MustElement(".codesearch-results p").MustText()31 fmt.Println(text)32 // Get all input elements. Rod supports query elements by css selector, xpath, and regex.33 // For more detailed usage, check the query_test.go file.34 fmt.Println("Found", len(page.MustElements("input")), "input elements")35 // Eval js on the page36 page.MustEval(`console.log("hello world")`)37 // Pass parameters as json objects to the js function. This MustEval will result 338 fmt.Println("1 + 2 =", page.MustEval(`(a, b) => a + b`, 1, 2).Int())39 // When eval on an element, "this" in the js is the current DOM element.40 fmt.Println(page.MustElement("title").MustEval(`this.innerText`).String())41 // Output:42 // Git is the most widely used version control system.43 // Found 5 input elements44 // 1 + 2 = 345 // Search · git · GitHub46}47// Shows how to disable headless mode and debug.48// Rod provides a lot of debug options, you can set them with setter methods or use environment variables.49// Doc for environment variables: https://pkg.go.dev/github.com/go-rod/rod/lib/defaults50func Example_disable_headless_to_debug() {51 // Headless runs the browser on foreground, you can also use env "rod=show"52 // Devtools opens the tab in each new tab opened automatically53 l := launcher.New().54 Headless(false).55 Devtools(true)56 defer l.Cleanup() // remove launcher.FlagUserDataDir57 url := l.MustLaunch()58 // Trace shows verbose debug information for each action executed59 // Slowmotion is a debug related function that waits 2 seconds between60 // each action, making it easier to inspect what your code is doing.61 browser := rod.New().62 ControlURL(url).63 Trace(true).64 SlowMotion(2 * time.Second).65 MustConnect()66 // ServeMonitor plays screenshots of each tab. This feature is extremely67 // useful when debugging with headless mode.68 // You can also enable it with env rod=monitor69 launcher.Open(browser.ServeMonitor(""))70 defer browser.MustClose()71 page := browser.MustPage("https://github.com/")72 page.MustElement("input").MustInput("git").MustPress(input.Enter)73 text := page.MustElement(".codesearch-results p").MustText()74 fmt.Println(text)75 utils.Pause() // pause goroutine76}77// Rod use https://golang.org/pkg/context to handle cancelations for IO blocking operations, most times it's timeout.78// Context will be recursively passed to all sub-methods.79// For example, methods like Page.Context(ctx) will return a clone of the page with the ctx,80// all the methods of the returned page will use the ctx if they have IO blocking operations.81// Page.Timeout or Page.WithCancel is just a shortcut for Page.Context.82// Of course, Browser or Element works the same way.83func Example_context_and_timeout() {84 page := rod.New().MustConnect().MustPage("https://github.com")85 page.86 // Set a 5-second timeout for all chained methods87 Timeout(5 * time.Second).88 // The total time for MustWaitLoad and MustElement must be less than 5 seconds89 MustWaitLoad().90 MustElement("title").91 // Methods after CancelTimeout won't be affected by the 5-second timeout92 CancelTimeout().93 // Set a 10-second timeout for all chained methods94 Timeout(10 * time.Second).95 // Panics if it takes more than 10 seconds96 MustText()97 // The two code blocks below are basically the same:98 {99 page.Timeout(5 * time.Second).MustElement("a").CancelTimeout()100 }101 {102 // Use this way you can customize your own way to cancel long-running task103 page, cancel := page.WithCancel()104 go func() {105 time.Sleep(time.Duration(rand.Int())) // cancel after randomly time106 cancel()107 }()108 page.MustElement("a")109 }110}111// We use "Must" prefixed functions to write example code. But in production you may want to use112// the no-prefix version of them.113// About why we use "Must" as the prefix, it's similar to https://golang.org/pkg/regexp/#MustCompile114func Example_error_handling() {115 page := rod.New().MustConnect().MustPage("https://mdn.dev")116 // We use Go's standard way to check error types, no magic.117 check := func(err error) {118 var evalErr *rod.ErrEval119 if errors.Is(err, context.DeadlineExceeded) { // timeout error120 fmt.Println("timeout err")121 } else if errors.As(err, &evalErr) { // eval error122 fmt.Println(evalErr.LineNumber)123 } else if err != nil {124 fmt.Println("can't handle", err)125 }126 }127 // The two code blocks below are doing the same thing in two styles:128 // The block below is better for debugging or quick scripting. We use panic to short-circuit logics.129 // So that we can take advantage of fluent interface (https://en.wikipedia.org/wiki/Fluent_interface)130 // and fail-fast (https://en.wikipedia.org/wiki/Fail-fast).131 // This style will reduce code, but it may also catch extra errors (less consistent and precise).132 {133 err := rod.Try(func() {134 fmt.Println(page.MustElement("a").MustHTML()) // use "Must" prefixed functions135 })136 check(err)137 }138 // The block below is better for production code. It's the standard way to handle errors.139 // Usually, this style is more consistent and precise.140 {141 el, err := page.Element("a")142 if err != nil {143 check(err)144 return145 }146 html, err := el.HTML()147 if err != nil {148 check(err)149 return150 }151 fmt.Println(html)152 }153}154// Example_search shows how to use Search to get element inside nested iframes or shadow DOMs.155// It works the same as https://developers.google.com/web/tools/chrome-devtools/dom#search156func Example_search() {157 browser := rod.New().MustConnect()158 defer browser.MustClose()159 page := browser.MustPage("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe")160 // Click the zoom-in button of the OpenStreetMap161 page.MustSearch(".leaflet-control-zoom-in").MustClick()162 fmt.Println("done")163 // Output: done164}165func Example_page_screenshot() {166 page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()167 // simple version168 page.MustScreenshot("my.png")169 // customization version170 img, _ := page.Screenshot(true, &proto.PageCaptureScreenshot{171 Format: proto.PageCaptureScreenshotFormatJpeg,172 Quality: 90,173 Clip: &proto.PageViewport{174 X: 0,175 Y: 0,176 Width: 300,177 Height: 200,178 Scale: 1,179 },180 FromSurface: true,181 })182 _ = utils.OutputFile("my.jpg", img)183}184func Example_page_pdf() {185 page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()186 // simple version187 page.MustPDF("my.pdf")188 // customized version189 pdf, _ := page.PDF(&proto.PagePrintToPDF{190 PaperWidth: 8.5,191 PaperHeight: 11,192 PageRanges: "1-3",193 })194 _ = utils.OutputFile("my.pdf", pdf)195}196// Show how to handle multiple results of an action.197// Such as when you login a page, the result can be success or wrong password.198func Example_race_selectors() {199 const username = ""200 const password = ""201 browser := rod.New().MustConnect()202 page := browser.MustPage("https://leetcode.com/accounts/login/")203 page.MustElement("#id_login").MustInput(username)204 page.MustElement("#id_password").MustInput(password).MustPress(input.Enter)205 // It will keep retrying until one selector has found a match206 elm := page.Race().Element(".nav-user-icon-base").MustHandle(func(e *rod.Element) {207 // print the username after successful login208 fmt.Println(*e.MustAttribute("title"))209 }).Element("[data-cy=sign-in-error]").MustDo()210 if elm.MustMatches("[data-cy=sign-in-error]") {211 // when wrong username or password212 panic(elm.MustText())213 }214}215// Rod uses mouse cursor to simulate clicks, so if a button is moving because of animation, the click may not work as expected.216// We usually use WaitStable to make sure the target isn't changing anymore.217func Example_wait_for_animation() {218 browser := rod.New().MustConnect()219 defer browser.MustClose()220 page := browser.MustPage("https://getbootstrap.com/docs/4.0/components/modal/")221 page.MustWaitLoad().MustElement("[data-target='#exampleModalLive']").MustClick()222 saveBtn := page.MustElementR("#exampleModalLive button", "Close")223 // Here, WaitStable will wait until the button's position and size become stable.224 saveBtn.MustWaitStable().MustClick().MustWaitInvisible()225 fmt.Println("done")226 // Output: done227}228// When you want to wait for an ajax request to complete, this example will be useful.229func Example_wait_for_request() {230 browser := rod.New().MustConnect()231 defer browser.MustClose()232 page := browser.MustPage("https://duckduckgo.com/")233 // Start to analyze request events234 wait := page.MustWaitRequestIdle()235 // This will trigger the search ajax request236 page.MustElement("#search_form_input_homepage").MustClick().MustInput("lisp")237 // Wait until there's no active requests238 wait()239 // We want to make sure that after waiting, there are some autocomplete240 // suggestions available.241 fmt.Println(len(page.MustElements(".search__autocomplete .acp")) > 0)242 // Output: true243}244// Shows how to change the retry/polling options that is used to query elements.245// This is useful when you want to customize the element query retry logic.246func Example_customize_retry_strategy() {247 browser := rod.New().MustConnect()248 defer browser.MustClose()249 page := browser.MustPage("https://github.com")250 // sleep for 0.5 seconds before every retry251 sleeper := func() utils.Sleeper {252 return func(context.Context) error {253 time.Sleep(time.Second / 2)254 return nil255 }256 }257 el, _ := page.Sleeper(sleeper).Element("input")258 fmt.Println(el.MustProperty("name"))259 // If sleeper is nil page.ElementE will query without retrying.260 // If nothing found it will return an error.261 el, err := page.Sleeper(rod.NotFoundSleeper).Element("input")262 if errors.Is(err, &rod.ErrElementNotFound{}) {263 fmt.Println("element not found")264 } else if err != nil {265 panic(err)266 }267 fmt.Println(el.MustProperty("name"))268 // Output:269 // q270 // q271}272// Shows how we can further customize the browser with the launcher library.273// Usually you use launcher lib to set the browser's command line flags (switches).274// Doc for flags: https://peter.sh/experiments/chromium-command-line-switches275func Example_customize_browser_launch() {276 url := launcher.New().277 Proxy("127.0.0.1:8080"). // set flag "--proxy-server=127.0.0.1:8080"278 Delete("use-mock-keychain"). // delete flag "--use-mock-keychain"279 MustLaunch()280 browser := rod.New().ControlURL(url).MustConnect()281 defer browser.MustClose()282 // So that we don't have to self issue certs for MITM283 browser.MustIgnoreCertErrors(true)284 // Adding authentication to the proxy, for the next auth request.285 // We use CLI tool "mitmproxy --proxyauth user:pass" as an example.286 go browser.MustHandleAuth("user", "pass")()287 // mitmproxy needs a cert config to support https. We use http here instead,288 // for example289 fmt.Println(browser.MustPage("https://mdn.dev/").MustElement("title").MustText())290}291// When rod doesn't have a feature that you need. You can easily call the cdp to achieve it.292// List of cdp API: https://github.com/go-rod/rod/tree/master/lib/proto293func Example_direct_cdp() {294 page := rod.New().MustConnect().MustPage()295 // Rod doesn't have a method to enable AD blocking,296 // but you can call cdp interface directly to achieve it.297 // The two code blocks below are equal to enable AD blocking298 {299 _ = proto.PageSetAdBlockingEnabled{300 Enabled: true,301 }.Call(page)302 }303 {304 // Interact with the cdp JSON API directly305 _, _ = page.Call(context.TODO(), "", "Page.setAdBlockingEnabled", map[string]bool{306 "enabled": true,307 })308 }309}310// Shows how to listen for events.311func Example_handle_events() {312 browser := rod.New().MustConnect()313 defer browser.MustClose()314 page := browser.MustPage()315 done := make(chan struct{})316 // Listen for all events of console output.317 go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {318 fmt.Println(page.MustObjectsToJSON(e.Args))319 close(done)320 })()321 wait := page.WaitEvent(&proto.PageLoadEventFired{})322 page.MustNavigate("https://mdn.dev")323 wait()324 // EachEvent allows us to achieve the same functionality as above.325 if false {326 // Subscribe events before they happen, run the "wait()" to start consuming327 // the events. We can return an optional stop signal to unsubscribe events.328 wait := page.EachEvent(func(e *proto.PageLoadEventFired) (stop bool) {329 return true330 })331 page.MustNavigate("https://mdn.dev")332 wait()333 }334 // Or the for-loop style to handle events to do the same thing above.335 if false {336 page.MustNavigate("https://mdn.dev")337 for msg := range page.Event() {338 e := proto.PageLoadEventFired{}339 if msg.Load(&e) {340 break341 }342 }343 }344 page.MustEval(`console.log("hello", "world")`)345 <-done346 // Output:347 // [hello world]348}349func Example_download_file() {350 browser := rod.New().MustConnect()351 page := browser.MustPage("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/")352 wait := browser.MustWaitDownload()353 page.MustElementR("a", "DOWNLOAD SAMPLE PDF FILE").MustClick()354 _ = utils.OutputFile("t.pdf", wait())355}356// Shows how to intercept requests and modify357// both the request and the response.358// The entire process of hijacking one request:359// browser --req-> rod ---> server ---> rod --res-> browser360// The --req-> and --res-> are the parts that can be modified.361func Example_hijack_requests() {362 browser := rod.New().MustConnect()363 defer browser.MustClose()364 router := browser.HijackRequests()365 defer router.MustStop()366 router.MustAdd("*.js", func(ctx *rod.Hijack) {367 // Here we update the request's header. Rod gives functionality to368 // change or update all parts of the request. Refer to the documentation369 // for more information.370 ctx.Request.Req().Header.Set("My-Header", "test")371 // LoadResponse runs the default request to the destination of the request.372 // Not calling this will require you to mock the entire response.373 // This can be done with the SetXxx (Status, Header, Body) functions on the374 // ctx.Response struct.375 _ = ctx.LoadResponse(http.DefaultClient, true)376 // Here we append some code to every js file.377 // The code will update the document title to "hi"378 ctx.Response.SetBody(ctx.Response.Body() + "\n document.title = 'hi' ")379 })380 go router.Run()381 browser.MustPage("https://go-rod.github.io").MustWait(`document.title === 'hi'`)382 fmt.Println("done")383 // Output: done384}385// Shows how to share a remote object reference between two Eval386func Example_eval_reuse_remote_object() {387 page := rod.New().MustConnect().MustPage()388 fn := page.MustEvaluate(rod.Eval(`Math.random`).ByObject())389 res := page.MustEval(`f => f()`, fn)390 // print a random number391 fmt.Println(res.Num())392}393// Shows how to update the state of the current page.394// In this example we enable the network domain.395func Example_states() {396 browser := rod.New().MustConnect()397 defer browser.MustClose()398 page := browser.MustPage()399 // LoadState detects whether the network domain is enabled or not.400 fmt.Println(page.LoadState(&proto.NetworkEnable{}))401 _ = proto.NetworkEnable{}.Call(page)402 // Check if the network domain is successfully enabled.403 fmt.Println(page.LoadState(&proto.NetworkEnable{}))404 // Output:405 // false406 // true407}408// We can use PagePool to concurrently control and reuse pages.409func ExamplePage_pool() {410 browser := rod.New().MustConnect()411 defer browser.MustClose()412 // We create a pool that will hold at most 3 pages which means the max concurrency is 3413 pool := rod.NewPagePool(3)414 // Create a page if needed415 create := func() *rod.Page {416 // We use MustIncognito to isolate pages with each other417 return browser.MustIncognito().MustPage()418 }419 yourJob := func() {420 page := pool.Get(create)421 defer pool.Put(page)422 page.MustNavigate("http://mdn.dev").MustWaitLoad()423 fmt.Println(page.MustInfo().Title)424 }425 // Run jobs concurrently426 wg := sync.WaitGroup{}427 for range "...." {428 wg.Add(1)429 go func() {430 defer wg.Done()431 yourJob()432 }()433 }434 wg.Wait()435 // cleanup pool436 pool.Cleanup(func(p *rod.Page) { p.MustClose() })437 // Output:438 // mdn.dev439 // mdn.dev440 // mdn.dev441 // mdn.dev442}443func Example_load_extension() {444 extPath, _ := filepath.Abs("fixtures/chrome-extension")445 u := launcher.New().446 // Must use abs path for an extension447 Set("load-extension", extPath).448 // Headless mode doesn't support extension yet.449 // Reason: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c5450 // You can use XVFB to get rid of it: https://github.com/go-rod/rod/blob/master/lib/examples/launch-managed/main.go451 Headless(false).452 MustLaunch()453 page := rod.New().ControlURL(u).MustConnect().MustPage("http://mdn.dev")454 page.MustWait(`document.title === 'test-extension'`)455 fmt.Println("ok")456 // Skip457 // Output: ok458}459func Example_log_cdp_traffic() {460 cdp := cdp.New(launcher.New().MustLaunch()).461 // Here we can customize how to log the requests, responses, and events transferred between Rod and the browser.462 Logger(utils.Log(func(msg ...interface{}) {463 // Such as use some fancy lib like github.com/davecgh/go-spew/spew to make the output more readable:464 // spew.Println(msg)465 // Here we use %#v as an example.466 fmt.Printf("%#v\n", msg)467 }))468 rod.New().Client(cdp).MustConnect().MustPage("http://mdn.dev")469}...

Full Screen

Full Screen

Example

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 title := page.MustElement("title").MustText()5 println(title)6 body := page.MustElement("body").MustHTML()7 println(body)8 title2 := page.MustElement(".title").MustText()9 println(title2)10 body2 := page.MustElement(".body").MustHTML()11 println(body2)12 title3 := page.MustElement("#title").MustText()13 println(title3)14 body3 := page.MustElement("#body").MustHTML()15 println(body3)16 title4 := page.MustElement("h1").MustText()17 println(title4)18 body4 := page.MustElement("p").MustHTML()19 println(body4)20 title5 := page.MustElement("h1.title").MustText()21 println(title5)22 body5 := page.MustElement("p.body").MustHTML()23 println(body5)24 title6 := page.MustElement("h1#title").MustText()25 println(title6)26 body6 := page.MustElement("p#body").MustHTML()27 println(body6)28 title7 := page.MustElement("h1.title#title").MustText()29 println(title7)30 body7 := page.MustElement("p.body#body").MustHTML()31 println(body

Full Screen

Full Screen

Example

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 element := page.Element("input[name=\"q\"]")5 fmt.Println(element.Text())6}

Full Screen

Full Screen

Example

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 l := launcher.New().Headless(false)4 defer l.Cleanup()5 url := l.MustLaunch()6 page.MustElement("input[name='q']").MustInput("rod")7 page.MustElement("input[name='btnK']").MustClick()8 fmt.Println(page.MustElement("h3").MustText())9}10--- PASS: Example (2.97s)

Full Screen

Full Screen

Example

Using AI Code Generation

copy

Full Screen

1import "github.com/go-rod/rod"2func main() {3 page := rod.New().MustConnect().MustPage(url)4 page.MustElement("input").MustInput("rod")5 page.MustElement("input").MustInput("rod").MustPress("Enter")6 page.MustScreenshot("rod.png")7}8import (9func Example() {10 fmt.Println("Example test")11}12func TestExample(t *testing.T) {13 Example()14}

Full Screen

Full Screen

Example

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 fmt.Println("Page Title", page.Title())5 fmt.Println("Page URL", page.URL())6}

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