Best Rod code snippet using rod.Connect
examples_test.go
Source:examples_test.go  
...19// This example opens https://github.com/, searches for "git",20// and then gets the header element which gives the description for Git.21func Example() {22	// Launch a new browser with default options, and connect to it.23	browser := rod.New().MustConnect()24	// Even you forget to close, rod will close it after main process ends.25	defer browser.MustClose()26	// Create a new page27	page := browser.MustPage("https://github.com")28	// We use css selector to get the search input element and input "git"29	page.MustElement("input").MustInput("git").MustType(input.Enter)30	// Wait until css selector get the element then get the text content of it.31	text := page.MustElement(".codesearch-results p").MustText()32	fmt.Println(text)33	// Get all input elements. Rod supports query elements by css selector, xpath, and regex.34	// For more detailed usage, check the query_test.go file.35	fmt.Println("Found", len(page.MustElements("input")), "input elements")36	// Eval js on the page37	page.MustEval(`() => console.log("hello world")`)38	// Pass parameters as json objects to the js function. This MustEval will result 339	fmt.Println("1 + 2 =", page.MustEval(`(a, b) => a + b`, 1, 2).Int())40	// When eval on an element, "this" in the js is the current DOM element.41	fmt.Println(page.MustElement("title").MustEval(`() => this.innerText`).String())42	// Output:43	// Git is the most widely used version control system.44	// Found 5 input elements45	// 1 + 2 = 346	// Search · git · GitHub47}48// Shows how to disable headless mode and debug.49// Rod provides a lot of debug options, you can set them with setter methods or use environment variables.50// Doc for environment variables: https://pkg.go.dev/github.com/go-rod/rod/lib/defaults51func Example_disable_headless_to_debug() {52	// Headless runs the browser on foreground, you can also use flag "-rod=show"53	// Devtools opens the tab in each new tab opened automatically54	l := launcher.New().55		Headless(false).56		Devtools(true)57	defer l.Cleanup() // remove launcher.FlagUserDataDir58	url := l.MustLaunch()59	// Trace shows verbose debug information for each action executed60	// Slowmotion is a debug related function that waits 2 seconds between61	// each action, making it easier to inspect what your code is doing.62	browser := rod.New().63		ControlURL(url).64		Trace(true).65		SlowMotion(2 * time.Second).66		MustConnect()67	// ServeMonitor plays screenshots of each tab. This feature is extremely68	// useful when debugging with headless mode.69	// You can also enable it with flag "-rod=monitor"70	launcher.Open(browser.ServeMonitor(""))71	defer browser.MustClose()72	page := browser.MustPage("https://github.com/")73	page.MustElement("input").MustInput("git").MustType(input.Enter)74	text := page.MustElement(".codesearch-results p").MustText()75	fmt.Println(text)76	utils.Pause() // pause goroutine77}78// Rod use https://golang.org/pkg/context to handle cancelations for IO blocking operations, most times it's timeout.79// Context will be recursively passed to all sub-methods.80// For example, methods like Page.Context(ctx) will return a clone of the page with the ctx,81// all the methods of the returned page will use the ctx if they have IO blocking operations.82// Page.Timeout or Page.WithCancel is just a shortcut for Page.Context.83// Of course, Browser or Element works the same way.84func Example_context_and_timeout() {85	page := rod.New().MustConnect().MustPage("https://github.com")86	page.87		// Set a 5-second timeout for all chained methods88		Timeout(5 * time.Second).89		// The total time for MustWaitLoad and MustElement must be less than 5 seconds90		MustWaitLoad().91		MustElement("title").92		// Methods after CancelTimeout won't be affected by the 5-second timeout93		CancelTimeout().94		// Set a 10-second timeout for all chained methods95		Timeout(10 * time.Second).96		// Panics if it takes more than 10 seconds97		MustText()98	// The two code blocks below are basically the same:99	{100		page.Timeout(5 * time.Second).MustElement("a").CancelTimeout()101	}102	{103		// Use this way you can customize your own way to cancel long-running task104		page, cancel := page.WithCancel()105		go func() {106			time.Sleep(time.Duration(rand.Int())) // cancel after randomly time107			cancel()108		}()109		page.MustElement("a")110	}111}112// We use "Must" prefixed functions to write example code. But in production you may want to use113// the no-prefix version of them.114// About why we use "Must" as the prefix, it's similar to https://golang.org/pkg/regexp/#MustCompile115func Example_error_handling() {116	page := rod.New().MustConnect().MustPage("https://mdn.dev")117	// We use Go's standard way to check error types, no magic.118	check := func(err error) {119		var evalErr *rod.ErrEval120		if errors.Is(err, context.DeadlineExceeded) { // timeout error121			fmt.Println("timeout err")122		} else if errors.As(err, &evalErr) { // eval error123			fmt.Println(evalErr.LineNumber)124		} else if err != nil {125			fmt.Println("can't handle", err)126		}127	}128	// The two code blocks below are doing the same thing in two styles:129	// The block below is better for debugging or quick scripting. We use panic to short-circuit logics.130	// So that we can take advantage of fluent interface (https://en.wikipedia.org/wiki/Fluent_interface)131	// and fail-fast (https://en.wikipedia.org/wiki/Fail-fast).132	// This style will reduce code, but it may also catch extra errors (less consistent and precise).133	{134		err := rod.Try(func() {135			fmt.Println(page.MustElement("a").MustHTML()) // use "Must" prefixed functions136		})137		check(err)138	}139	// The block below is better for production code. It's the standard way to handle errors.140	// Usually, this style is more consistent and precise.141	{142		el, err := page.Element("a")143		if err != nil {144			check(err)145			return146		}147		html, err := el.HTML()148		if err != nil {149			check(err)150			return151		}152		fmt.Println(html)153	}154}155// Example_search shows how to use Search to get element inside nested iframes or shadow DOMs.156// It works the same as https://developers.google.com/web/tools/chrome-devtools/dom#search157func Example_search() {158	browser := rod.New().MustConnect()159	defer browser.MustClose()160	page := browser.MustPage("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe")161	// Click the zoom-in button of the OpenStreetMap162	page.MustSearch(".leaflet-control-zoom-in").MustClick()163	fmt.Println("done")164	// Output: done165}166func Example_page_screenshot() {167	page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()168	// simple version169	page.MustScreenshot("my.png")170	// customization version171	img, _ := page.Screenshot(true, &proto.PageCaptureScreenshot{172		Format:  proto.PageCaptureScreenshotFormatJpeg,173		Quality: gson.Int(90),174		Clip: &proto.PageViewport{175			X:      0,176			Y:      0,177			Width:  300,178			Height: 200,179			Scale:  1,180		},181		FromSurface: true,182	})183	_ = utils.OutputFile("my.jpg", img)184}185func Example_page_pdf() {186	page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()187	// simple version188	page.MustPDF("my.pdf")189	// customized version190	pdf, _ := page.PDF(&proto.PagePrintToPDF{191		PaperWidth:  gson.Num(8.5),192		PaperHeight: gson.Num(11),193		PageRanges:  "1-3",194	})195	_ = utils.OutputFile("my.pdf", pdf)196}197// Show how to handle multiple results of an action.198// Such as when you login a page, the result can be success or wrong password.199func Example_race_selectors() {200	const username = ""201	const password = ""202	browser := rod.New().MustConnect()203	page := browser.MustPage("https://leetcode.com/accounts/login/")204	page.MustElement("#id_login").MustInput(username)205	page.MustElement("#id_password").MustInput(password).MustType(input.Enter)206	// It will keep retrying until one selector has found a match207	elm := page.Race().Element(".nav-user-icon-base").MustHandle(func(e *rod.Element) {208		// print the username after successful login209		fmt.Println(*e.MustAttribute("title"))210	}).Element("[data-cy=sign-in-error]").MustDo()211	if elm.MustMatches("[data-cy=sign-in-error]") {212		// when wrong username or password213		panic(elm.MustText())214	}215}216// Rod uses mouse cursor to simulate clicks, so if a button is moving because of animation, the click may not work as expected.217// We usually use WaitStable to make sure the target isn't changing anymore.218func Example_wait_for_animation() {219	browser := rod.New().MustConnect()220	defer browser.MustClose()221	page := browser.MustPage("https://getbootstrap.com/docs/4.0/components/modal/")222	page.MustWaitLoad().MustElement("[data-target='#exampleModalLive']").MustClick()223	saveBtn := page.MustElementR("#exampleModalLive button", "Close")224	// Here, WaitStable will wait until the button's position and size become stable.225	saveBtn.MustWaitStable().MustClick().MustWaitInvisible()226	fmt.Println("done")227	// Output: done228}229// When you want to wait for an ajax request to complete, this example will be useful.230func Example_wait_for_request() {231	browser := rod.New().MustConnect()232	defer browser.MustClose()233	page := browser.MustPage("https://www.wikipedia.org/").MustWaitLoad()234	// Start to analyze request events235	wait := page.MustWaitRequestIdle()236	// This will trigger the search ajax request237	page.MustElement("#searchInput").MustClick().MustInput("lisp")238	// Wait until there's no active requests239	wait()240	// We want to make sure that after waiting, there are some autocomplete241	// suggestions available.242	fmt.Println(len(page.MustElements(".suggestion-link")) > 0)243	// Output: true244}245// Shows how to change the retry/polling options that is used to query elements.246// This is useful when you want to customize the element query retry logic.247func Example_customize_retry_strategy() {248	browser := rod.New().MustConnect()249	defer browser.MustClose()250	page := browser.MustPage("https://github.com")251	// sleep for 0.5 seconds before every retry252	sleeper := func() utils.Sleeper {253		return func(context.Context) error {254			time.Sleep(time.Second / 2)255			return nil256		}257	}258	el, _ := page.Sleeper(sleeper).Element("input")259	fmt.Println(el.MustProperty("name"))260	// If sleeper is nil page.ElementE will query without retrying.261	// If nothing found it will return an error.262	el, err := page.Sleeper(rod.NotFoundSleeper).Element("input")263	if errors.Is(err, &rod.ErrElementNotFound{}) {264		fmt.Println("element not found")265	} else if err != nil {266		panic(err)267	}268	fmt.Println(el.MustProperty("name"))269	// Output:270	// q271	// q272}273// Shows how we can further customize the browser with the launcher library.274// Usually you use launcher lib to set the browser's command line flags (switches).275// Doc for flags: https://peter.sh/experiments/chromium-command-line-switches276func Example_customize_browser_launch() {277	url := launcher.New().278		Proxy("127.0.0.1:8080").     // set flag "--proxy-server=127.0.0.1:8080"279		Delete("use-mock-keychain"). // delete flag "--use-mock-keychain"280		MustLaunch()281	browser := rod.New().ControlURL(url).MustConnect()282	defer browser.MustClose()283	// So that we don't have to self issue certs for MITM284	browser.MustIgnoreCertErrors(true)285	// Adding authentication to the proxy, for the next auth request.286	// We use CLI tool "mitmproxy --proxyauth user:pass" as an example.287	go browser.MustHandleAuth("user", "pass")()288	// mitmproxy needs a cert config to support https. We use http here instead,289	// for example290	fmt.Println(browser.MustPage("https://mdn.dev/").MustElement("title").MustText())291}292// When rod doesn't have a feature that you need. You can easily call the cdp to achieve it.293// List of cdp API: https://github.com/go-rod/rod/tree/master/lib/proto294func Example_direct_cdp() {295	page := rod.New().MustConnect().MustPage()296	// Rod doesn't have a method to enable AD blocking,297	// but you can call cdp interface directly to achieve it.298	// The two code blocks below are equal to enable AD blocking299	{300		_ = proto.PageSetAdBlockingEnabled{301			Enabled: true,302		}.Call(page)303	}304	{305		// Interact with the cdp JSON API directly306		_, _ = page.Call(context.TODO(), "", "Page.setAdBlockingEnabled", map[string]bool{307			"enabled": true,308		})309	}310}311// Shows how to listen for events.312func Example_handle_events() {313	browser := rod.New().MustConnect()314	defer browser.MustClose()315	page := browser.MustPage()316	done := make(chan struct{})317	// Listen for all events of console output.318	go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {319		fmt.Println(page.MustObjectsToJSON(e.Args))320		close(done)321	})()322	wait := page.WaitEvent(&proto.PageLoadEventFired{})323	page.MustNavigate("https://mdn.dev")324	wait()325	// EachEvent allows us to achieve the same functionality as above.326	if false {327		// Subscribe events before they happen, run the "wait()" to start consuming328		// the events. We can return an optional stop signal to unsubscribe events.329		wait := page.EachEvent(func(e *proto.PageLoadEventFired) (stop bool) {330			return true331		})332		page.MustNavigate("https://mdn.dev")333		wait()334	}335	// Or the for-loop style to handle events to do the same thing above.336	if false {337		page.MustNavigate("https://mdn.dev")338		for msg := range page.Event() {339			e := proto.PageLoadEventFired{}340			if msg.Load(&e) {341				break342			}343		}344	}345	page.MustEval(`() => console.log("hello", "world")`)346	<-done347	// Output:348	// [hello world]349}350func Example_download_file() {351	browser := rod.New().MustConnect()352	page := browser.MustPage("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/")353	wait := browser.MustWaitDownload()354	page.MustElementR("a", "DOWNLOAD SAMPLE PDF FILE").MustClick()355	_ = utils.OutputFile("t.pdf", wait())356}357// Shows how to intercept requests and modify358// both the request and the response.359// The entire process of hijacking one request:360//361//	browser --req-> rod ---> server ---> rod --res-> browser362//363// The --req-> and --res-> are the parts that can be modified.364func Example_hijack_requests() {365	browser := rod.New().MustConnect()366	defer browser.MustClose()367	router := browser.HijackRequests()368	defer router.MustStop()369	router.MustAdd("*.js", func(ctx *rod.Hijack) {370		// Here we update the request's header. Rod gives functionality to371		// change or update all parts of the request. Refer to the documentation372		// for more information.373		ctx.Request.Req().Header.Set("My-Header", "test")374		// LoadResponse runs the default request to the destination of the request.375		// Not calling this will require you to mock the entire response.376		// This can be done with the SetXxx (Status, Header, Body) functions on the377		// ctx.Response struct.378		_ = ctx.LoadResponse(http.DefaultClient, true)379		// Here we append some code to every js file.380		// The code will update the document title to "hi"381		ctx.Response.SetBody(ctx.Response.Body() + "\n document.title = 'hi' ")382	})383	go router.Run()384	browser.MustPage("https://go-rod.github.io").MustWait(`() => document.title === 'hi'`)385	fmt.Println("done")386	// Output: done387}388// Shows how to share a remote object reference between two Eval389func Example_eval_reuse_remote_object() {390	page := rod.New().MustConnect().MustPage()391	fn := page.MustEvaluate(rod.Eval(`() => Math.random`).ByObject())392	res := page.MustEval(`f => f()`, fn)393	// print a random number394	fmt.Println(res.Num())395}396// Shows how to update the state of the current page.397// In this example we enable the network domain.398func Example_states() {399	browser := rod.New().MustConnect()400	defer browser.MustClose()401	page := browser.MustPage()402	// LoadState detects whether the network domain is enabled or not.403	fmt.Println(page.LoadState(&proto.NetworkEnable{}))404	_ = proto.NetworkEnable{}.Call(page)405	// Check if the network domain is successfully enabled.406	fmt.Println(page.LoadState(&proto.NetworkEnable{}))407	// Output:408	// false409	// true410}411// We can use PagePool to concurrently control and reuse pages.412func ExamplePage_pool() {413	browser := rod.New().MustConnect()414	defer browser.MustClose()415	// We create a pool that will hold at most 3 pages which means the max concurrency is 3416	pool := rod.NewPagePool(3)417	// Create a page if needed418	create := func() *rod.Page {419		// We use MustIncognito to isolate pages with each other420		return browser.MustIncognito().MustPage()421	}422	yourJob := func() {423		page := pool.Get(create)424		defer pool.Put(page)425		page.MustNavigate("http://mdn.dev").MustWaitLoad()426		fmt.Println(page.MustInfo().Title)427	}428	// Run jobs concurrently429	wg := sync.WaitGroup{}430	for range "...." {431		wg.Add(1)432		go func() {433			defer wg.Done()434			yourJob()435		}()436	}437	wg.Wait()438	// cleanup pool439	pool.Cleanup(func(p *rod.Page) { p.MustClose() })440	// Output:441	// mdn.dev442	// mdn.dev443	// mdn.dev444	// mdn.dev445}446func Example_load_extension() {447	extPath, _ := filepath.Abs("fixtures/chrome-extension")448	u := launcher.New().449		// Must use abs path for an extension450		Set("load-extension", extPath).451		// Headless mode doesn't support extension yet.452		// Reason: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c5453		// You can use XVFB to get rid of it: https://github.com/go-rod/rod/blob/master/lib/examples/launch-managed/main.go454		Headless(false).455		MustLaunch()456	page := rod.New().ControlURL(u).MustConnect().MustPage("http://mdn.dev")457	page.MustWait(`() => document.title === 'test-extension'`)458	fmt.Println("ok")459	// Skip460	// Output: ok461}462func Example_log_cdp_traffic() {463	cdp := cdp.New().464		// Here we can customize how to log the requests, responses, and events transferred between Rod and the browser.465		Logger(utils.Log(func(args ...interface{}) {466			switch v := args[0].(type) {467			case *cdp.Request:468				fmt.Printf("id: %d", v.ID)469			}470		})).471		Start(cdp.MustConnectWS(launcher.New().MustLaunch()))472	rod.New().Client(cdp).MustConnect().MustPage("http://mdn.dev")473}...main.go
Source:main.go  
...19	// Available flags: https://peter.sh/experiments/chromium-command-line-switches20	l.Set("disable-gpu").Delete("disable-gpu")21	// Launch with headful mode22	l.Headless(false).XVFB("--server-num=5", "--server-args=-screen 0 1600x900x16")23	browser := rod.New().Client(l.MustClient()).MustConnect()24	// You may want to start a server to watch the screenshots of the remote browser.25	launcher.Open(browser.ServeMonitor(""))26	fmt.Println(27		browser.MustPage("https://mdn.dev/").MustEval("() => document.title"),28	)29	utils.Pause()30}...Connect
Using AI Code Generation
1import (  2func main() {  3    l := launcher.New().Bin("/path/to/chrome")4    defer l.Cleanup()5    browser := rod.New().ControlURL(l).Connect()6    title := page.MustElement("title").MustText()7    fmt.Println(title)8}Connect
Using AI Code Generation
1import (2func main() {3	browser := rod.New().Connect()4	title, err := page.Title()5	if err != nil {6		panic(err)7	}8	fmt.Println(title)9}10import (11func main() {12	browser := rod.New().Launch()13	title, err := page.Title()14	if err != nil {15		panic(err)16	}17	fmt.Println(title)18}19import (20func main() {21	browser := rod.New().Launch()22	title, err := page.Title()23	if err != nil {24		panic(err)25	}26	fmt.Println(title)27}28import (29func main() {30	browser := rod.New().Launch()31	title, err := page.Title()32	if err != nil {33		panic(err)34	}35	fmt.Println(title)36}37import (38func main() {39	browser := rod.New().Launch()Connect
Using AI Code Generation
1import (2func main() {3    browser := rod.New().Connect()4    defer browser.Close()5    defer page.Close()6    if err != nil {7        fmt.Println(err)8    }9    fmt.Println("Page loaded")10}11import (12func main() {13    browser := rod.New().Launch()14    defer browser.Close()15    defer page.Close()16    if err != nil {17        fmt.Println(err)18    }19    fmt.Println("Page loaded")20}Connect
Using AI Code Generation
1import (2func main() {3	browser := rod.New().Connect()4	page := browser.Page("")5	title := page.Title()6	fmt.Println(title)7}Connect
Using AI Code Generation
1import (2func main() {3	browser := rod.New().Connect()4	page.Element(".navbar-brand").MustText()5	fmt.Println(page)6}Connect
Using AI Code Generation
1import (2func main() {3    browser := rod.New().Connect()4    title := page.Title()5    fmt.Println(title)6}Connect
Using AI Code Generation
1import (2func main() {3	l := launcher.New().Headless(false).Devtools(false)4	browser := rod.New().ControlURL(l).Connect()5	page.WaitLoad()6	title := page.MustTitle()7	fmt.Println(title)8}9import (Connect
Using AI Code Generation
1import (2func main() {3    l := launcher.New().Headless(false).Delete("default", "default")4    defer l.Cleanup()5    browser := rod.New().ControlURL(l).MustConnect()6    page := browser.MustPage("Connect
Using AI Code Generation
1import (2func main() {3    browser := rod.New().Connect()4    page.WaitLoad()5    title := page.MustTitle()6    fmt.Println("Page title:", title)7}8import (9func main() {10    browser := rod.New().Launch()11    page.WaitLoad()12    title := page.MustTitle()13    fmt.Println("Page title:", title)14}15import (16func main() {17    browser := rod.New()18    page.WaitLoad()19    title := page.MustTitle()20    fmt.Println("Page title:", title)21}22import (23func main() {24    browser := rod.NewBrowser()25    page.WaitLoad()Connect
Using AI Code Generation
1import (2func main() {3    browser := rod.New().Connect()4    page.Element("input[name=q]").Input("rod")5    page.Keyboard.Press("Enter")6    page.WaitLoad()7    title := page.MustTitle()8    fmt.Printf("Page title: %s9    browser.MustClose()10}11import (12func main() {13    browser := rod.New().Connect()14    page.Element("input[name=q]").Input("rod")15    page.Keyboard.Press("Enter")16    page.WaitLoad()17    page.WaitElement(".g").MustText()18    title := page.MustTitle()19    fmt.Printf("Page title: %s20    browser.MustClose()21}22import (23func main() {24    browser := rod.New().Connect()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!!
