Best Rod code snippet using rod.Browser
rod-helper.go
Source:rod-helper.go
...12)13/**14 * @Description: æ°å»ºä¸ä¸ªæ¯æ代çç browser 对象15 * @param httpProxyURL http://127.0.0.1:1080916 * @return *rod.Browser17 * @return error18 */19func NewBrowser(httpProxyURL string) (*rod.Browser, error) {20 var browser *rod.Browser21 err := rod.Try(func() {22 u := launcher.New().23 Proxy(httpProxyURL).24 MustLaunch()25 browser = rod.New().ControlURL(u).MustConnect()26 })27 if err != nil {28 return nil, err29 }30 return browser, nil31}32/**33 * @Description: 访é®ç®æ Urlï¼è¿å pageï¼åªæ¯è¿ä¸ª page ææï¼å¦æå次åºåå
¶ä»çäºä»¶æ æ34 * @param desURL ç®æ Url35 * @param httpProxyURL http://127.0.0.1:1080936 * @param timeOut è¶
æ¶æ¶é´37 * @param maxRetryTimes å½æ¯éè¶
æ¶ err çæ¶åï¼æå¤å¯ä»¥éè¯å 次38 * @return *rod.Page39 * @return error40 */41func NewBrowserFromDocker(httpProxyURL, remoteDockerURL string) (*rod.Browser, error) {42 var browser *rod.Browser43 err := rod.Try(func() {44 l := launcher.MustNewRemote(remoteDockerURL)45 u := l.Proxy(httpProxyURL).MustLaunch()46 l.Headless(false).XVFB()47 browser = rod.New().Client(l.Client()).ControlURL(u).MustConnect()48 })49 if err != nil {50 return nil, err51 }52 return browser, nil53}54func NewPage(browser *rod.Browser) (*rod.Page, error) {55 page, err := browser.Page(proto.TargetCreateTarget{URL: ""})56 if err != nil {57 return nil, err58 }59 return page, err60}61func NewPageNavigate(browser *rod.Browser, desURL string, timeOut time.Duration, maxRetryTimes int) (*rod.Page, error) {62 page, err := NewPage(browser)63 if err != nil {64 return nil, err65 }66 page = page.Timeout(timeOut)67 nowRetryTimes := 068 for nowRetryTimes <= maxRetryTimes {69 err = rod.Try(func() {70 wait := page.MustWaitNavigation()71 page.MustNavigate(desURL)72 wait()73 })74 if errors.Is(err, context.DeadlineExceeded) {75 // è¶
æ¶76 return nil, err77 } else if err == nil {78 // 没æé®é¢79 return page, nil80 }81 }82 return nil, err83}84func PageNavigate(page *rod.Page, desURL string, timeOut time.Duration, maxRetryTimes int) (*rod.Page, error) {85 var err error86 page = page.Timeout(timeOut)87 nowRetryTimes := 088 for nowRetryTimes <= maxRetryTimes {89 err = rod.Try(func() {90 wait := page.MustWaitNavigation()91 page.MustNavigate(desURL)92 wait()93 })94 if errors.Is(err, context.DeadlineExceeded) {95 // è¶
æ¶96 return nil, err97 } else if err == nil {98 // 没æé®é¢99 return page, nil100 }101 }102 return nil, err103}104/**105 * @Description: 访é®ç®æ Urlï¼è¿å pageï¼åªæ¯è¿ä¸ª page ææï¼å¦æå次åºåå
¶ä»çäºä»¶æ æ106 * @param desURL ç®æ Url107 * @param httpProxyURL http://127.0.0.1:10809108 * @param timeOut è¶
æ¶æ¶é´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 // 设置代ç...
storeschecker.go
Source:storeschecker.go
...24 if err != nil {25 s.logger.Error("Failed to create control URL.", zap.Error(err))26 return []stores.StockCheckResult{}27 }28 browser, err := s.createBrowser(url)29 if err != nil {30 s.logger.Error("Failed to create browser.", zap.Error(err))31 return []stores.StockCheckResult{}32 }33 defer func() {34 err := browser.Close()35 if err != nil {36 s.logger.Error("Failed to close browser.", zap.Error(err))37 }38 }()39 pool := rod.NewPagePool(s.config.PagePoolSize)40 defer pool.Cleanup(func(p *rod.Page) {41 err := p.Close()42 if err != nil {43 s.logger.Error("Failed to close page.", zap.Error(err))44 }45 })46 c := make(chan stores.StockCheckResult)47 get := s.createGetPageFunc(browser, pool)48 release := s.createReleasePageFunc(pool)49 for _, s := range storesSlice {50 go func(store stores.Store) {51 c <- store.Check(get, release)52 }(s)53 }54 numOfStores := len(storesSlice)55 results := make([]stores.StockCheckResult, 0, numOfStores)56 for i := 0; i < numOfStores; i++ {57 results = append(results, <-c)58 }59 return results60}61func (s StoresChecker) createControlURL() (string, error) {62 launcher := launcher.New().Set("--no-sandbox")63 launcher.Devtools(s.config.DevTools)64 launcher.Headless(s.config.Headless)65 return launcher.Launch()66}67func (s StoresChecker) createBrowser(url string) (*rod.Browser, error) {68 browser := rod.New().ControlURL(url)69 browser.Logger(newCustomRodLogger(s.logger))70 browser.Trace(s.config.Trace)71 if s.config.SlowMotion {72 browser.SlowMotion(time.Second)73 }74 err := browser.Connect()75 if err != nil {76 return nil, err77 }78 return browser, nil79}80func (s StoresChecker) createGetPageFunc(browser *rod.Browser, pool rod.PagePool) func() *rod.Page {81 create := s.createCreatePageFunc(browser)82 // Gets a page from the pool and configures a timeout for store to perform all operations with it83 return func() *rod.Page {84 // TODO Implement timeout85 return pool.Get(create)86 }87}88func (s StoresChecker) createReleasePageFunc(pool rod.PagePool) func(*rod.Page) {89 return func(page *rod.Page) {90 // TODO Implement cancel timeout91 pool.Put(page)92 }93}94func (s StoresChecker) createCreatePageFunc(browser *rod.Browser) func() *rod.Page {95 // This func will create a new configured page will be contained within a different incognito browser window.96 // It returns nil when an error occurs rather than exposing error due to https://pkg.go.dev/github.com/go-rod/rod#PagePool.Get97 return func() *rod.Page {98 browser, err := browser.Incognito()99 if err != nil {100 s.logger.Error("Failed to create incognito browser.", zap.Error(err))101 return nil102 }103 page, err := bypass.Page(browser)104 if err != nil {105 s.logger.Error("Failed to create page.", zap.Error(err))106 return nil107 }108 return page...
main.go
Source:main.go
...19 login()20 }21 lock.Lock()22 defer lock.Unlock()23 browser := newBrowser(true)24 defer browser.Close()25 page := browser.MustPage("https://www.futunn.com/account/home").MustWaitLoad()26 page.Race().Element("#signIn .none").MustHandle(func(el *rod.Element) {27 el.MustClick()28 log.Println("ç¾å°æå")29 }).ElementR("#signed", "å·²ç¾å°").MustHandle(func(el *rod.Element) {30 log.Println("å·²ç»ç¾è¿å°äº")31 }).MustDo()32}33func isLoggedIn() bool {34 lock.Lock()35 defer lock.Unlock()36 browser := newBrowser(true)37 defer browser.Close()38 return browser.MustPage("https://www.futunn.com").MustWaitLoad().MustHasR("a", "éåº|Sign Out")39}40func login() {41 lock.Lock()42 defer lock.Unlock()43 browser := newBrowser(false)44 defer browser.Close()45 page := browser.MustPage("https://passport.futunn.com/?target=https%3A%2F%2Fwww.futunn.com%2Faccount%2Fhome&lang=zh-hk#login")46 page.MustElement(`input[name=email]`).MustInput(*email)47 page.MustElement(`input[name=password]`).MustInput(*password).MustPress(input.Enter)48 page.Race().Element(".nn-header-account").MustHandle(func(e *rod.Element) {49 log.Println("ç»å½æåï¼å·²ç»æ¾å°ç»å½å页é¢å
ç´ å
容 ", e.MustText())50 }).Element(".u-error-wrapper").MustHandle(func(e *rod.Element) {51 // å½ç¨æ·åæå¯ç é误æ¶52 log.Println("失败")53 log.Panicln(e)54 log.Fatal(e.MustText())55 })56}57func newBrowser(headless bool) *rod.Browser {58 url := launcher.New().Headless(headless).UserDataDir("tmp/user").MustLaunch()59 return rod.New().ControlURL(url).MustConnect()60}...
Browser
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 page.MustElement("input[name=q]").MustInput("rod").MustPress(proto.InputKeyEventEnter)5 page.MustScreenshot("rod.png")6}7import (8func main() {9 browser := rod.New().MustConnect()10 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")11 page.MustScreenshot("rod.png")12}13import (14func main() {15 browser := rod.New().MustConnect()16 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")17 page.MustScreenshot("rod.png")18}19import (20func main() {21 browser := rod.New().MustConnect()22 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")23 page.MustScreenshot("rod.png")24}25import (26func main() {27 browser := rod.New().MustConnect()28 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")29 page.MustScreenshot("rod.png")30}31import (32func main() {33 browser := rod.New().MustConnect()34 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")35 page.MustScreenshot("rod.png")36}
Browser
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Bin("/usr/bin/chromium-browser").Headless(false).MustLaunch()4 defer l.Close()5 b := rod.New().ControlURL(l).MustConnect()6 defer b.Close()7 page.MustElement("input").MustInput("rod")8 page.MustElement("input").MustPress("Enter")9 page.MustScreenshot("rod.png")10 log.Println("done")11}
Browser
Using AI Code Generation
1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 page.MustScreenshot("screenshot.png")5}6import (7func main() {8 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()9 page.MustScreenshot("screenshot.png")10}11import (12func main() {13 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()14 page.MustScreenshot("screenshot.png")15}16import (17func main() {18 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()19 page.MustScreenshot("screenshot.png")20}21import (22func main() {23 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()24 page.MustScreenshot("screenshot.png")25}26import (
Browser
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 title := page.Element("title").Text()5 fmt.Println(title)6}
Browser
Using AI Code Generation
1import (2func main() {3}4import (5func main() {6 fmt.Println(p.MustInfo())7}8import (9func main() {10 e := p.MustElement("div")11 fmt.Println(e.MustInfo())12}13import (14func main() {15 e := p.MustElement("div")16 fmt.Println(e.MustEval(`() => {17 }`))18}19import (20func main() {21 e := p.MustElement("div")22 fmt.Println(e.MustEval(`() => {23 }`))24}25import (26func main() {
Browser
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}9import "fmt"10func main() {11 fmt.Println("Hello, World!")12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16}17import "fmt"18func main() {19 fmt.Println("Hello, World!")20}21import "fmt"22func main() {23 fmt.Println("Hello, World!")24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}29import "fmt"30func main() {31 fmt.Println("Hello, World!")32}33import "fmt"34func main() {35 fmt.Println("Hello, World!")36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40}41import "fmt"42func main() {43 fmt.Println("Hello, World!")44}45import "fmt"46func main() {47 fmt.Println("Hello, World!")48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52}53import "fmt"54func main() {55 fmt.Println("Hello,
Browser
Using AI Code Generation
1import "fmt"2func main(){3 r := rod.New()4 e := p.Element("input[name='q']")5 e.Input("Hello World")6 e.Press("enter")7 p.WaitLoad()8 t := p.Title()9 fmt.Println(t)10}
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!!