How to use Load method of rod Package

Best Rod code snippet using rod.Load

examples_test.go

Source:examples_test.go Github

copy

Full Screen

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

Full Screen

Full Screen

rod_base.go

Source:rod_base.go Github

copy

Full Screen

...30 }31 return NewBrowserBase(rodOptions.Log,32 localChromeFPath,33 rodOptions.Settings.AdvancedSettings.ProxySettings.GetLocalHttpProxyUrl(),34 rodOptions.LoadAdblock,35 rodOptions.PreLoadUrl())36 } else {37 return NewBrowserBaseFromDocker(rodOptions.Settings.AdvancedSettings.ProxySettings.GetLocalHttpProxyUrl(),38 rodOptions.Settings.ExperimentalFunction.RemoteChromeSettings.RemoteDockerURL,39 rodOptions.Settings.ExperimentalFunction.RemoteChromeSettings.RemoteAdblockPath,40 rodOptions.Settings.ExperimentalFunction.RemoteChromeSettings.ReMoteUserDataDir,41 rodOptions.LoadAdblock,42 rodOptions.PreLoadUrl())43 }44}45func NewBrowserBase(log *logrus.Logger, localChromeFPath, httpProxyURL string, loadAdblock bool, preLoadUrl ...string) (*rod.Browser, error) {46 var err error47 once.Do(func() {48 adblockSavePath, err = releaseAdblock(log)49 if err != nil {50 log.Errorln("releaseAdblock", err)51 log.Panicln("releaseAdblock", err)52 }53 })54 // 随机的 rod 子文件夹名称55 nowUserData := filepath.Join(pkg.DefRodTmpRootFolder(), my_util.RandStringBytesMaskImprSrcSB(20))56 var browser *rod.Browser57 if localChromeFPath != "" {58 // 如果有指定的 chrome 路径,则使用指定的 chrome 路径59 if my_util.IsFile(localChromeFPath) == false {60 log.Errorln(errors.New("localChromeFPath is not a file, localChromePath:" + localChromeFPath))61 panic(errors.New("localChromeFPath is not a file, localChromePath:" + localChromeFPath))62 }63 err = rod.Try(func() {64 purl := ""65 if loadAdblock == true {66 purl = launcher.New().Bin(localChromeFPath).67 Delete("disable-extensions").68 Set("load-extension", adblockSavePath).69 Proxy(httpProxyURL).70 Headless(false). // 插件模式需要设置这个71 UserDataDir(nowUserData).72 //XVFB("--server-num=5", "--server-args=-screen 0 1600x900x16").73 //XVFB("-ac :99", "-screen 0 1280x1024x16").74 MustLaunch()75 } else {76 purl = launcher.New().Bin(localChromeFPath).77 Proxy(httpProxyURL).78 UserDataDir(nowUserData).79 MustLaunch()80 }81 browser = rod.New().ControlURL(purl).MustConnect()82 })83 } else {84 // 如果没有指定 chrome 的路径,则使用 rod 自行下载的 chrome85 err = rod.Try(func() {86 purl := ""87 if loadAdblock == true {88 purl = launcher.New().89 Delete("disable-extensions").90 Set("load-extension", adblockSavePath).91 Proxy(httpProxyURL).92 Headless(false). // 插件模式需要设置这个93 UserDataDir(nowUserData).94 //XVFB("--server-num=5", "--server-args=-screen 0 1600x900x16").95 //XVFB("-ac :99", "-screen 0 1280x1024x16").96 MustLaunch()97 } else {98 purl = launcher.New().99 Proxy(httpProxyURL).100 UserDataDir(nowUserData).101 MustLaunch()102 }103 browser = rod.New().ControlURL(purl).MustConnect()104 })105 }106 if err != nil {107 return nil, err108 }109 // 如果加载了插件,那么就需要进行一定的耗时操作,等待其第一次的加载完成110 if loadAdblock == true {111 _, _, err := HttpGetFromBrowser(browser, "https://www.qq.com", 15*time.Second)112 if err != nil {113 if browser != nil {114 browser.Close()115 }116 return nil, err117 }118 //if page != nil {119 // _ = page.Close()120 //}121 }122 if len(preLoadUrl) > 0 && preLoadUrl[0] != "" {123 _, _, err := HttpGetFromBrowser(browser, preLoadUrl[0], 15*time.Second)124 if err != nil {125 if browser != nil {126 browser.Close()127 }128 return nil, err129 }130 //if page != nil {131 // _ = page.Close()132 //}133 }134 return browser, nil135}136func NewBrowserBaseFromDocker(httpProxyURL, remoteDockerURL string, remoteAdblockPath, reMoteUserDataDir string,137 loadAdblock bool, preLoadUrl ...string) (*rod.Browser, error) {138 var browser *rod.Browser139 err := rod.Try(func() {140 purl := ""141 var l *launcher.Launcher142 if loadAdblock == true {143 l = launcher.MustNewManaged(remoteDockerURL)144 purl = l.Delete("disable-extensions").145 Set("load-extension", remoteAdblockPath).146 Proxy(httpProxyURL).147 Headless(false). // 插件模式需要设置这个148 UserDataDir(reMoteUserDataDir).149 MustLaunch()150 } else {151 l = launcher.MustNewManaged(remoteDockerURL)152 purl = l.153 Proxy(httpProxyURL).154 UserDataDir(reMoteUserDataDir).155 MustLaunch()156 }157 browser = rod.New().Client(l.MustClient()).ControlURL(purl).MustConnect()158 })159 if err != nil {160 return nil, err161 }162 // 如果加载了插件,那么就需要进行一定的耗时操作,等待其第一次的加载完成163 if loadAdblock == true {164 _, page, err := HttpGetFromBrowser(browser, "https://www.qq.com", 15*time.Second)165 if err != nil {166 if browser != nil {167 browser.Close()168 }169 return nil, err170 }171 if page != nil {172 _ = page.Close()173 }174 }175 if len(preLoadUrl) > 0 && preLoadUrl[0] != "" {176 _, page, err := HttpGetFromBrowser(browser, preLoadUrl[0], 15*time.Second)177 if err != nil {178 if browser != nil {179 browser.Close()180 }181 return nil, err182 }183 if page != nil {184 _ = page.Close()185 }186 }187 return browser, nil188}189func NewPageNavigate(browser *rod.Browser, desURL string, timeOut time.Duration, debugMode ...bool) (*rod.Page, int, string, error) {190 addSleepTime := time.Second * 5191 if len(debugMode) > 0 && debugMode[0] == true {192 addSleepTime = 0 * time.Second193 }194 page, err := newPage(browser)195 if err != nil {196 return nil, 0, "", err197 }198 return PageNavigate(page, desURL, timeOut+addSleepTime)199}200func NewPageNavigateWithProxy(browser *rod.Browser, proxyUrl string, desURL string, timeOut time.Duration) (*rod.Page, int, string, error) {201 page, err := newPage(browser)202 if err != nil {203 return nil, 0, "", err204 }205 return PageNavigateWithProxy(page, proxyUrl, desURL, timeOut)206}207func PageNavigate(page *rod.Page, desURL string, timeOut time.Duration) (*rod.Page, int, string, error) {208 err := page.SetUserAgent(&proto.NetworkSetUserAgentOverride{209 UserAgent: random_useragent.RandomUserAgent(true),210 })211 if err != nil {212 if page != nil {213 page.Close()214 }215 return nil, 0, "", err216 }217 var e proto.NetworkResponseReceived218 wait := page.WaitEvent(&e)219 page = page.Timeout(timeOut)220 err = rod.Try(func() {221 page.MustNavigate(desURL)222 wait()223 })224 if err != nil {225 if page != nil {226 page.Close()227 }228 return nil, 0, "", err229 }230 // 出去前把 TimeOUt 取消了231 page = page.CancelTimeout()232 Status := e.Response.Status233 ResponseURL := e.Response.URL234 //if Status >= 400 {235 // publicIP := "xx.xx.xx.xx"236 // publicIP, err = GetPublicIP(page, timeOut, nil)237 // if err != nil {238 // return nil, 0, "", errors.New(fmt.Sprintf("status code >= 400, PublicIP: %v, Status is %d, ResponseURL is %v", publicIP, Status, ResponseURL))239 // }240 // if page != nil {241 // _ = page.Close()242 // }243 // return nil, Status, ResponseURL, errors.New(fmt.Sprintf("status code >= 400, PublicIP: %v, Status is %d, ResponseURL is %v", publicIP, Status, ResponseURL))244 //}245 return page, Status, ResponseURL, nil246}247func PageNavigateWithProxy(page *rod.Page, proxyUrl string, desURL string, timeOut time.Duration) (*rod.Page, int, string, error) {248 router := page.HijackRequests()249 defer router.Stop()250 router.MustAdd("*", func(ctx *rod.Hijack) {251 px, _ := url.Parse(proxyUrl)252 err := ctx.LoadResponse(&http.Client{253 Transport: &http.Transport{254 Proxy: http.ProxyURL(px),255 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},256 },257 }, true)258 if err != nil {259 return260 }261 })262 go router.Run()263 err := page.SetUserAgent(&proto.NetworkSetUserAgentOverride{264 UserAgent: random_useragent.RandomUserAgent(true),265 })266 if err != nil {...

Full Screen

Full Screen

rod-helper.go

Source:rod-helper.go Github

copy

Full Screen

...109 * @param maxRetryTimes 当是非超时 err 的时候,最多可以重试几次110 * @return *rod.Page111 * @return error112 */113func NewBrowserLoadPage(desURL string, httpProxyURL string, timeOut time.Duration, maxRetryTimes int) (*rod.Page, error) {114 browser, err := NewBrowser(httpProxyURL)115 if err != nil {116 return nil, err117 }118 page, err := browser.Page(proto.TargetCreateTarget{URL: ""})119 if err != nil {120 return nil, err121 }122 page = page.Timeout(timeOut)123 nowRetryTimes := 0124 for nowRetryTimes <= maxRetryTimes {125 err = rod.Try(func() {126 wait := page.MustWaitNavigation()127 page.MustNavigate(desURL)128 wait()129 })130 if errors.Is(err, context.DeadlineExceeded) {131 // 超时132 return nil, err133 } else if err == nil {134 // 没有问题135 return page, nil136 }137 }138 return nil, err139}140/**141 * @Description: 访问目标 Url,返回 page,只是这个 page 有效,如果再次出发其他的事件无效142 * @param desURL 目标 Url143 * @param httpProxyURL http://127.0.0.1:10809144 * @param timeOut 超时时间145 * @param maxRetryTimes 当是非超时 err 的时候,最多可以重试几次146 * @return *rod.Page147 * @return error148 */149func NewBrowserLoadPageFromRemoteDocker(desURL string, httpProxyURL, remoteDockerURL string, timeOut time.Duration, maxRetryTimes int) (*rod.Page, error) {150 browser, err := NewBrowserFromDocker(httpProxyURL, remoteDockerURL)151 if err != nil {152 return nil, err153 }154 page, err := browser.Page(proto.TargetCreateTarget{URL: ""})155 if err != nil {156 return nil, err157 }158 page = page.Timeout(timeOut)159 nowRetryTimes := 0160 for nowRetryTimes <= maxRetryTimes {161 err = rod.Try(func() {162 wait := page.MustWaitNavigation()163 page.MustNavigate(desURL)164 wait()165 })166 if errors.Is(err, context.DeadlineExceeded) {167 // 超时168 return nil, err169 } else if err == nil {170 // 没有问题171 break172 }173 }174 return page, nil175}176/**177 * @Description: 访问目标 Url,返回 page,只是这个 page 有效,如果再次出发其他的事件无效178 * @param desURL 目标 Url179 * @param httpProxyURL http://127.0.0.1:10809180 * @param timeOut 超时时间181 * @param maxRetryTimes 当是非超时 err 的时候,最多可以重试几次182 * @return *rod.Page183 * @return error184 */185func NewBrowserLoadPageByHijackRequests(desURL string, httpProxyURL string, timeOut time.Duration, maxRetryTimes int) (*rod.Page, error) {186 var page *rod.Page187 var err error188 // 创建一个 page189 browser := rod.New()190 err = browser.Connect()191 if err != nil {192 return nil, err193 }194 page, err = browser.Page(proto.TargetCreateTarget{URL: ""})195 if err != nil {196 return nil, err197 }198 page = page.Timeout(timeOut)199 // 设置代理200 router := page.HijackRequests()201 defer router.Stop()202 err = rod.Try(func() {203 router.MustAdd("*", func(ctx *rod.Hijack) {204 px, _ := url.Parse(httpProxyURL)205 ctx.LoadResponse(&http.Client{206 Transport: &http.Transport{207 Proxy: http.ProxyURL(px),208 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},209 },210 Timeout: timeOut,211 }, true)212 })213 })214 if err != nil {215 return nil ,err216 }217 go router.Run()218 nowRetryTimes := 0219 for nowRetryTimes <= maxRetryTimes {220 err = rod.Try(func() {221 page.MustNavigate(desURL).MustWaitLoad()222 })223 if errors.Is(err, context.DeadlineExceeded) {224 // 超时225 return nil, err226 } else if err == nil {227 // 没有问题228 break229 }230 time.Sleep(time.Second)231 nowRetryTimes++232 }233 return page, nil234}...

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.Element("#hplogo").MustWaitVisible().MustScreenshot("screenshot.png")5 page.Keyboard.MustPress(input.Enter)6 page.Keyboard.MustType("Rod")7 page.Keyboard.MustPress(input.Enter)8 page.Screenshot("screenshot2.png")9 fmt.Println(page.MustElement(".g").MustText())10}

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Open("image.png")4 if err != nil {5 fmt.Println(err)6 os.Exit(1)7 }8 defer file.Close()9 img, err := png.Decode(file)10 if err != nil {11 fmt.Println(err)12 os.Exit(1)13 }14 bounds := img.Bounds()15 newImage := image.NewRGBA(bounds)16 draw.Draw(newImage, bounds, img, bounds.Min, draw.Src)17 distance := math.Sqrt(float64((width/2)*(width/2) + (height/2)*(height/2)))18 for i := 0; i < 50; i++ {19 for x := 0; x < width; x++ {20 for y := 0; y < height; y++ {21 r, g, b, a := img.At(x, y).RGBA()22 dist := math.Sqrt(float64((width/2-x)*(width/2-x) + (height/2-y)*(height/2-y)))23 intensity := (distance - dist) / distance

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 page.WaitLoad()4 title, err := page.Title()5 if err != nil {6 fmt.Println("Error in getting title")7 }8 fmt.Println("Title is: ", title)9 url, err := page.URL()10 if err != nil {11 fmt.Println("Error in getting url")12 }13 fmt.Println("URL is: ", url)14 html, err := page.HTML()15 if err != nil {16 fmt.Println("Error in getting html")17 }18 fmt.Println("HTML is: ", html)19 browser.Close()20}

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.WaitLoad()5 title, _ := page.Title()6 fmt.Println(title)7}

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 bitmap := robotgo.LoadBitmap("logo.png")4 x, y := robotgo.FindBitmap(bitmap)5 fmt.Println("pos:", x, y)6 robotgo.FreeBitmap(bitmap)7}

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 bmp := robotgo.OpenBitmap("2.png")4 x, y := robotgo.FindBitmap(bmp)5 fmt.Println("Position of the image: ", x, y)6 robotgo.MoveMouse(x, y)7}

Full Screen

Full Screen

Load

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r.Load(20)4 fmt.Println("length of rod is ", r.Length)5 fmt.Println("weight of rod is ", r.Weight)6 fmt.Println("price of rod is ", r.Price)7}

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