Documentation ¶
Overview ¶
Example (Basic) ¶
Example_basic is a simple test that opens https://github.com/, searches for "git", and then gets the header element which gives the description for Git.
package main import ( "context" "errors" "fmt" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/input" ) func main() { // Launch a new browser with default options, and connect to it. browser := rod.New().Connect() // Even you forget to close, rod will close it after main process ends. defer browser.Close() // Timeout will be passed to all chained function calls. // The code will panic out if any chained call is used after the timeout. page := browser.Timeout(time.Minute).Page("https://github.com") // Resize the window make sure window size is always consistent. page.Window(0, 0, 1200, 600) // We use css selector to get the search input element and input "git" page.Element("input").Input("git").Press(input.Enter) // Wait until css selector get the element then get the text content of it. // You can also pass multiple selectors to race the result, useful when dealing with multiple possible results. text := page.Element(".codesearch-results p").Text() fmt.Println(text) // Get all input elements. Rod supports query elements by css selector, xpath, and regex. // For more detailed usage, check the query_test.go file. fmt.Println(len(page.Elements("input"))) // Eval js on the page page.Eval(`console.log("hello world")`) // Pass parameters as json objects to the js function. This one will return 3 fmt.Println(page.Eval(`(a, b) => a + b`, 1, 2).Int()) // When eval on an element, you can use "this" to access the DOM element. fmt.Println(page.Element("title").Eval(`this.innerText`).String()) // To handle errors in rod, you can use rod.Try or E suffixed function family like "page.ElementE" // https://github.com/go-rod/rod#q-why-functions-dont-return-error-values err := rod.Try(func() { // Here we will catch timeout or query error page.Timeout(time.Second / 2).Element("element-not-exists") }) if errors.Is(err, context.DeadlineExceeded) { fmt.Println("after 0.5 seconds, the element is still not rendered") } }
Output: Git is the most widely used version control system. 5 3 Search · git · GitHub after 0.5 seconds, the element is still not rendered
Example (Customize_browser_launch) ¶
Example_customize_browser_launch will show how we can further customise the browser with the launcher library. The launcher lib comes with many default flags (switches), this example adds and removes a few.
package main import ( "fmt" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/launcher" ) func main() { // Documentation for default switches can be found at the source of the // launcher.New function, as well as at // https://peter.sh/experiments/chromium-command-line-switches/. url := launcher.New(). // Set a flag- Adding the HTTP proxy server. Set("proxy-server", "127.0.0.1:8080"). // Delete a flag- remove the mock-keychain flag Delete("use-mock-keychain"). Launch() browser := rod.New().ControlURL(url).Connect() defer browser.Close() // Adding authentication to the proxy, for the next auth request. // We use CLI tool "mitmproxy --proxyauth user:pass" as an example. browser.HandleAuth("user", "pass") // mitmproxy needs a cert config to support https. We use http here instead, // for example fmt.Println(browser.Page("http://example.com/").Element("title").Text()) // Skip
Output:
Example (Customize_retry_strategy) ¶
Example_customize_retry_strategy allows us to change the retry/polling options that is used to query elements. This is useful when you want to customize the element query retry logic.
package main import ( "context" "errors" "fmt" "time" "github.com/go-rod/rod" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("https://github.com") // sleep for 0.5 seconds before every retry sleeper := func(context.Context) error { time.Sleep(time.Second / 2) return nil } el, _ := page.ElementE(sleeper, "", []string{"input"}) // If sleeper is nil page.ElementE will query without retrying. // If nothing found it will return an error. el, err := page.ElementE(nil, "", []string{"input"}) if errors.Is(err, rod.ErrElementNotFound) { fmt.Println("element not found") } else if err != nil { panic(err) } fmt.Println(el.Eval(`this.name`).String()) }
Output: q
Example (Direct_cdp) ¶
Example_direct_cdp shows how we can use Rod when it doesn't have a function or a feature that you would like to use. You can easily call the cdp interface.
package main import ( "encoding/json" "fmt" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/proto" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() // The code here shows how SetCookies works. // Normally, you use something like // browser.Page("").SetCookies(...).Navigate(url). page := browser.Page("") // Call the cdp interface directly. // We set the cookie before we visit the website. // The "proto" lib contains every JSON schema you may need to communicate // with browser res, err := proto.NetworkSetCookie{ Name: "rod", Value: "test", URL: "https://example.com", }.Call(page) if err != nil { panic(err) } fmt.Println(res.Success) page.Navigate("https://example.com") // Eval injects a script into the page. We use this to return the cookies // that JS detects to validate our cdp call. cookie := page.Eval(`document.cookie`).String() fmt.Println(cookie) // You can also use your own raw JSON to send a json request. params, _ := json.Marshal(map[string]string{ "name": "rod", "value": "test", "url": "https://example.com", }) ctx, client, sessionID := page.CallContext() _, _ = client.Call(ctx, sessionID, "Network.SetCookie", params) }
Output: true rod=test
Example (Handle_events) ¶
Example_handle_events is an example showing how we can use Rod to subscribe to events.
package main import ( "fmt" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/proto" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("") done := make(chan int) // Listen to all events of console output. go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) { log := page.ObjectsToJSON(e.Args).Join(" ") fmt.Println(log) close(done) })() wait := page.WaitEvent(&proto.PageLoadEventFired{}) page.Navigate("https://example.com") wait() // EachEvent allows us to achieve the same functionality as above. if false { // Subscribe events before they happen, run the "wait()" to start consuming // the events. We can return an optional stop signal unsubscribe events. wait := page.EachEvent(func(e *proto.PageLoadEventFired) (stop bool) { return true }) page.Navigate("https://example.com") wait() } page.Eval(`console.log("hello", "world")`) <-done }
Output: hello world
Example (Headless_with_debug) ¶
Example_headless_with_debug shows how we can start a browser with debug information and headless mode disabled to show the browser in the foreground. Rod provides a lot of debug options, you can use the Set method to enable them or use environment variables. (Default environment variables can be found in "lib/defaults").
package main import ( "fmt" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/input" "github.com/go-rod/rod/lib/launcher" ) func main() { // Headless runs the browser on foreground, you can also use env "rod=show" // Devtools opens the tab in each new tab opened automatically url := launcher.New(). Headless(false). Devtools(true). Launch() // Trace shows verbose debug information for each action executed // Slowmotion is a debug related function that waits 2 seconds between // each action, making it easier to inspect what your code is doing. browser := rod.New(). Timeout(time.Minute). ControlURL(url). Trace(true). Slowmotion(2 * time.Second). Connect() // ServeMonitor plays screenshots of each tab. This feature is extremely // useful when debugging with headless mode. browser.ServeMonitor(":9777", true) defer browser.Close() page := browser.Page("https://www.wikipedia.org/") page.Element("#searchLanguage").Select("[lang=zh]") page.Element("#searchInput").Input("热干面") page.Keyboard.Press(input.Enter) fmt.Println(page.Element("#firstHeading").Text()) // Response gets the binary of the image as a []byte. img := page.Element(`[alt="Hot Dry Noodles.jpg"]`).Resource() fmt.Println(len(img)) // print the size of the image // Pause temporarily halts JavaScript execution on the website. // You can resume execution in the devtools window by clicking the resume // button in the "source" tab. page.Pause() // Skip
Output:
Example (Hijack_requests) ¶
Example_hijack_requests shows how we can intercept requests and modify both the request and the response.
package main import ( "fmt" "time" "github.com/go-rod/rod" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() router := browser.HijackRequests() defer router.Stop() router.Add("*.js", func(ctx *rod.Hijack) { // Here we update the request's header. Rod gives functionality to // change or update all parts of the request. Refer to the documentation // for more information. ctx.Request.SetHeader("My-Header", "test") // LoadResponse runs the default request to the destination of the request. // Not calling this will require you to mock the entire response. // This can be done with the SetXxx (Status, Header, Body) functions on the // response struct. ctx.LoadResponse() // Here we append some code to every js file. // The code will update the document title to "hi" ctx.Response.SetBody(ctx.Response.StringBody() + "\n document.title = 'hi' ") }) go router.Run() browser.Page("https://www.wikipedia.org/").Wait(`document.title === 'hi'`) fmt.Println("done") }
Output: done
Example (Search) ¶
Example_search shows how to use Search to get element inside nested iframes or shadow DOMs. It works the same as https://developers.google.com/web/tools/chrome-devtools/dom#search
package main import ( "fmt" "time" "github.com/go-rod/rod" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe") // get the code mirror editor inside the iframe el := page.Search(".CodeMirror") fmt.Println(*el.Attribute("class")) }
Output: CodeMirror cm-s-default CodeMirror-wrap
Example (States) ¶
Example_states allows us to update the state of the current page. In this example we enable network access.
package main import ( "fmt" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/proto" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("") // LoadState detects whether the network is enabled or not. fmt.Println(page.LoadState(&proto.NetworkEnable{})) _ = proto.NetworkEnable{}.Call(page) // Now that we called the request on the page, we check see if the state // result updates to true. fmt.Println(page.LoadState(&proto.NetworkEnable{})) }
Output: false true
Example (Wait_for_animation) ¶
Example_wait_for_animation is an example to simulate humans more accurately. If a button is moving too fast, you cannot click it as a human. To more accurately simulate human inputs, actions triggered by Rod can be based on mouse point location, so you can allow Rod to wait for the button to become stable before it tries clicking it.
package main import ( "fmt" "time" "github.com/go-rod/rod" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("https://getbootstrap.com/docs/4.0/components/modal/") page.WaitLoad().Element("[data-target='#exampleModalLive']").Click() saveBtn := page.ElementMatches("#exampleModalLive button", "Close") // Here, WaitStable will wait until the save button's position becomes // stable. The timeout is 5 seconds, after which it times out (or after 1 // minute since the browser was created). Timeouts from parents are // inherited to the children as well. saveBtn.Timeout(5 * time.Second).WaitStable().Click().WaitInvisible() fmt.Println("done") }
Output: done
Example (Wait_for_request) ¶
Example_wait_for_request shows an example where Rod will wait for all requests on the page to complete (such as network request) before interacting with the page.
package main import ( "fmt" "time" "github.com/go-rod/rod" ) func main() { browser := rod.New().Timeout(time.Minute).Connect() defer browser.Close() page := browser.Page("https://duckduckgo.com/") // WaitRequestIdle will wait for all possible ajax calls to complete before // continuing on with further execution calls. wait := page.WaitRequestIdle() page.Element("#search_form_input_homepage").Click().Input("test") time.Sleep(300 * time.Millisecond) // Wait for js debounce. wait() // We want to make sure that after waiting, there are some autocomplete // suggestions available. fmt.Println(len(page.Elements(".search__autocomplete .acp")) > 0) }
Output: true
Index ¶
- Variables
- func Event(msg *cdp.Event, evt proto.Payload) bool
- func SprintFnThis(js string) string
- func Try(fn func()) (err error)
- type Array
- type Browser
- func (b *Browser) CDPCall(c CDPCall) *Browser
- func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params json.RawMessage) (res []byte, err error)
- func (b *Browser) CallContext() (context.Context, proto.Client, string)
- func (b *Browser) CancelTimeout() *Browser
- func (b *Browser) Client(c *cdp.Client) *Browser
- func (b *Browser) Close()
- func (b *Browser) CloseE() error
- func (b *Browser) Connect() *Browser
- func (b *Browser) ConnectE() (err error)
- func (b *Browser) Context(ctx context.Context, cancel func()) *Browser
- func (b *Browser) ControlURL(url string) *Browser
- func (b *Browser) DisableDomain(ctx context.Context, sessionID proto.TargetSessionID, method proto.Payload) (recover func())
- func (b *Browser) EachEvent(fn interface{}) (wait func())
- func (b *Browser) EnableDomain(ctx context.Context, sessionID proto.TargetSessionID, method proto.Payload) (recover func())
- func (b *Browser) Event() *goob.Observable
- func (b *Browser) GetContext() context.Context
- func (b *Browser) HandleAuth(username, password string)
- func (b *Browser) HandleAuthE(username, password string) func() error
- func (b *Browser) HijackRequests() *HijackRouter
- func (b *Browser) Incognito() *Browser
- func (b *Browser) IncognitoE() (*Browser, error)
- func (b *Browser) LoadState(sessionID proto.TargetSessionID, method proto.Payload) (has bool)
- func (b *Browser) Page(url string) *Page
- func (b *Browser) PageE(url string) (*Page, error)
- func (b *Browser) PageFromTargetID(targetID proto.TargetTargetID) *Page
- func (b *Browser) PageFromTargetIDE(targetID proto.TargetTargetID) (*Page, error)
- func (b *Browser) Pages() Pages
- func (b *Browser) PagesE() (Pages, error)
- func (b *Browser) Quiet(quiet bool) *Browser
- func (b *Browser) ServeMonitor(host string, openBrowser bool) *kit.ServerContext
- func (b *Browser) Slowmotion(delay time.Duration) *Browser
- func (b *Browser) Timeout(d time.Duration) *Browser
- func (b *Browser) Trace(enable bool) *Browser
- func (b *Browser) TraceLog(msg func(string), js func(string, Array), err func(error)) *Browser
- func (b *Browser) WaitEvent(e proto.Payload) (wait func())
- type CDPCall
- type Element
- func (el *Element) Attribute(name string) *string
- func (el *Element) AttributeE(name string) (*string, error)
- func (el *Element) Blur() *Element
- func (el *Element) BlurE() error
- func (el *Element) Box() *proto.DOMRect
- func (el *Element) BoxE() (*proto.DOMRect, error)
- func (el *Element) CallContext() (context.Context, proto.Client, string)
- func (el *Element) CancelTimeout() *Element
- func (el *Element) CanvasToImage(format string, quality float64) []byte
- func (el *Element) CanvasToImageE(format string, quality float64) ([]byte, error)
- func (el *Element) Click() *Element
- func (el *Element) ClickE(button proto.InputMouseButton) error
- func (el *Element) Clickable() bool
- func (el *Element) ClickableE() (bool, error)
- func (el *Element) ContainsElement(target *Element) bool
- func (el *Element) ContainsElementE(target *Element) (bool, error)
- func (el *Element) Context(ctx context.Context, cancel func()) *Element
- func (el *Element) Describe() *proto.DOMNode
- func (el *Element) DescribeE(depth int, pierce bool) (*proto.DOMNode, error)
- func (el *Element) Element(selector string) *Element
- func (el *Element) ElementByJS(js string, params ...interface{}) *Element
- func (el *Element) ElementByJSE(js string, params Array) (*Element, error)
- func (el *Element) ElementE(selectors ...string) (*Element, error)
- func (el *Element) ElementMatches(selector, regex string) *Element
- func (el *Element) ElementMatchesE(pairs ...string) (*Element, error)
- func (el *Element) ElementX(xpath string) *Element
- func (el *Element) ElementXE(xPaths ...string) (*Element, error)
- func (el *Element) Elements(selector string) Elements
- func (el *Element) ElementsByJS(js string, params ...interface{}) Elements
- func (el *Element) ElementsByJSE(js string, params Array) (Elements, error)
- func (el *Element) ElementsE(selector string) (Elements, error)
- func (el *Element) ElementsX(xpath string) Elements
- func (el *Element) ElementsXE(xpath string) (Elements, error)
- func (el *Element) Eval(js string, params ...interface{}) proto.JSON
- func (el *Element) EvalE(byValue bool, js string, params Array) (*proto.RuntimeRemoteObject, error)
- func (el *Element) Focus() *Element
- func (el *Element) FocusE() error
- func (el *Element) Frame() *Page
- func (el *Element) GetContext() context.Context
- func (el *Element) HTML() string
- func (el *Element) HTMLE() (string, error)
- func (el *Element) Has(selector string) bool
- func (el *Element) HasE(selector string) (bool, error)
- func (el *Element) HasMatches(selector, regex string) bool
- func (el *Element) HasMatchesE(selector, regex string) (bool, error)
- func (el *Element) HasX(selector string) bool
- func (el *Element) HasXE(selector string) (bool, error)
- func (el *Element) Hover() *Element
- func (el *Element) HoverE() error
- func (el *Element) Input(text string) *Element
- func (el *Element) InputE(text string) error
- func (el *Element) Matches(selector string) bool
- func (el *Element) MatchesE(selector string) (bool, error)
- func (el *Element) Next() *Element
- func (el *Element) NextE() (*Element, error)
- func (el *Element) NodeID() proto.DOMNodeID
- func (el *Element) NodeIDE() (proto.DOMNodeID, error)
- func (el *Element) Parent() *Element
- func (el *Element) ParentE() (*Element, error)
- func (el *Element) Parents(selector string) Elements
- func (el *Element) ParentsE(selector string) (Elements, error)
- func (el *Element) Press(key rune) *Element
- func (el *Element) PressE(key rune) error
- func (el *Element) Previous() *Element
- func (el *Element) PreviousE() (*Element, error)
- func (el *Element) Property(name string) proto.JSON
- func (el *Element) PropertyE(name string) (proto.JSON, error)
- func (el *Element) Release()
- func (el *Element) ReleaseE() error
- func (el *Element) Resource() []byte
- func (el *Element) ResourceE() ([]byte, error)
- func (el *Element) Screenshot(toFile ...string) []byte
- func (el *Element) ScreenshotE(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error)
- func (el *Element) ScrollIntoView() *Element
- func (el *Element) ScrollIntoViewE() error
- func (el *Element) Select(selectors ...string) *Element
- func (el *Element) SelectAllText() *Element
- func (el *Element) SelectAllTextE() error
- func (el *Element) SelectE(selectors []string) error
- func (el *Element) SelectText(regex string) *Element
- func (el *Element) SelectTextE(regex string) error
- func (el *Element) SetFiles(paths ...string) *Element
- func (el *Element) SetFilesE(paths []string) error
- func (el *Element) ShadowRoot() *Element
- func (el *Element) ShadowRootE() (*Element, error)
- func (el *Element) Text() string
- func (el *Element) TextE() (string, error)
- func (el *Element) Timeout(d time.Duration) *Element
- func (el *Element) Trace(msg string) (removeOverlay func())
- func (el *Element) Visible() bool
- func (el *Element) VisibleE() (bool, error)
- func (el *Element) Wait(js string, params ...interface{}) *Element
- func (el *Element) WaitE(js string, params Array) error
- func (el *Element) WaitInvisible() *Element
- func (el *Element) WaitInvisibleE() error
- func (el *Element) WaitLoad() *Element
- func (el *Element) WaitLoadE() error
- func (el *Element) WaitStable() *Element
- func (el *Element) WaitStableE(interval time.Duration) error
- func (el *Element) WaitVisible() *Element
- func (el *Element) WaitVisibleE() error
- type Elements
- type Error
- type Hijack
- type HijackRequest
- func (ctx *HijackRequest) Body() string
- func (ctx *HijackRequest) Header(key string) string
- func (ctx *HijackRequest) Headers() proto.NetworkHeaders
- func (ctx *HijackRequest) JSONBody() gjson.Result
- func (ctx *HijackRequest) Method() string
- func (ctx *HijackRequest) SetBody(obj interface{}) *HijackRequest
- func (ctx *HijackRequest) SetClient(client *http.Client) *HijackRequest
- func (ctx *HijackRequest) SetHeader(pairs ...string) *HijackRequest
- func (ctx *HijackRequest) SetMethod(name string) *HijackRequest
- func (ctx *HijackRequest) SetQuery(pairs ...interface{}) *HijackRequest
- func (ctx *HijackRequest) SetURL(url string) *HijackRequest
- func (ctx *HijackRequest) Type() proto.NetworkResourceType
- func (ctx *HijackRequest) URL() *url.URL
- type HijackResponse
- func (ctx *HijackResponse) Body() []byte
- func (ctx *HijackResponse) BodyE() ([]byte, error)
- func (ctx *HijackResponse) BodyStream() io.Reader
- func (ctx *HijackResponse) BodyStreamE() (io.Reader, error)
- func (ctx *HijackResponse) Fail(reason proto.NetworkErrorReason) *HijackResponse
- func (ctx *HijackResponse) Header(key string) string
- func (ctx *HijackResponse) HeaderE(key string) (string, error)
- func (ctx *HijackResponse) Headers() http.Header
- func (ctx *HijackResponse) HeadersE() (http.Header, error)
- func (ctx *HijackResponse) JSONBody() gjson.Result
- func (ctx *HijackResponse) SetBody(obj interface{}) *HijackResponse
- func (ctx *HijackResponse) SetHeader(pairs ...string)
- func (ctx *HijackResponse) SetStatusCode(code int)
- func (ctx *HijackResponse) StatusCode() int
- func (ctx *HijackResponse) StatusCodeE() (int, error)
- func (ctx *HijackResponse) StringBody() string
- type HijackRouter
- func (r *HijackRouter) Add(pattern string, handler func(*Hijack))
- func (r *HijackRouter) AddE(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error
- func (r *HijackRouter) Remove(pattern string)
- func (r *HijackRouter) RemoveE(pattern string) error
- func (r *HijackRouter) Run()
- func (r *HijackRouter) Stop()
- func (r *HijackRouter) StopE() error
- type Keyboard
- func (k *Keyboard) Down(key rune) *Keyboard
- func (k *Keyboard) DownE(key rune) error
- func (k *Keyboard) InsertText(text string) *Keyboard
- func (k *Keyboard) InsertTextE(text string) error
- func (k *Keyboard) Press(key rune) *Keyboard
- func (k *Keyboard) PressE(key rune) error
- func (k *Keyboard) Up(key rune) *Keyboard
- func (k *Keyboard) UpE(key rune) error
- type Mouse
- func (m *Mouse) Click(button proto.InputMouseButton) *Mouse
- func (m *Mouse) ClickE(button proto.InputMouseButton) error
- func (m *Mouse) Down(button proto.InputMouseButton) *Mouse
- func (m *Mouse) DownE(button proto.InputMouseButton, clicks int64) error
- func (m *Mouse) Move(x, y float64) *Mouse
- func (m *Mouse) MoveE(x, y float64, steps int) error
- func (m *Mouse) Scroll(x, y float64) *Mouse
- func (m *Mouse) ScrollE(offsetX, offsetY float64, steps int) error
- func (m *Mouse) Up(button proto.InputMouseButton) *Mouse
- func (m *Mouse) UpE(button proto.InputMouseButton, clicks int64) error
- type Page
- func (p *Page) AddScriptTag(url string) *Page
- func (p *Page) AddScriptTagE(url, content string) error
- func (p *Page) AddStyleTag(url string) *Page
- func (p *Page) AddStyleTagE(url, content string) error
- func (p *Page) CallContext() (context.Context, proto.Client, string)
- func (p *Page) CancelTimeout() *Page
- func (p *Page) Close()
- func (p *Page) CloseE() error
- func (p *Page) Context(ctx context.Context, cancel func()) *Page
- func (p *Page) Cookies(urls ...string) []*proto.NetworkCookie
- func (p *Page) CookiesE(urls []string) ([]*proto.NetworkCookie, error)
- func (p *Page) DisableDomain(method proto.Payload) (recover func())
- func (p *Page) EachEvent(fn interface{}) (wait func())
- func (p *Page) Element(selectors ...string) *Element
- func (p *Page) ElementByJS(js string, params ...interface{}) *Element
- func (p *Page) ElementByJSE(sleeper kit.Sleeper, thisID proto.RuntimeRemoteObjectID, js string, ...) (*Element, error)
- func (p *Page) ElementE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, selectors []string) (*Element, error)
- func (p *Page) ElementFromNode(id proto.DOMNodeID) *Element
- func (p *Page) ElementFromNodeE(id proto.DOMNodeID) (*Element, error)
- func (p *Page) ElementFromObject(id proto.RuntimeRemoteObjectID) *Element
- func (p *Page) ElementFromPoint(left, top int) *Element
- func (p *Page) ElementFromPointE(x, y int64) (*Element, error)
- func (p *Page) ElementMatches(pairs ...string) *Element
- func (p *Page) ElementMatchesE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, pairs []string) (*Element, error)
- func (p *Page) ElementX(xPaths ...string) *Element
- func (p *Page) ElementXE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, xPaths []string) (*Element, error)
- func (p *Page) Elements(selector string) Elements
- func (p *Page) ElementsByJS(js string, params ...interface{}) Elements
- func (p *Page) ElementsByJSE(thisID proto.RuntimeRemoteObjectID, js string, params Array) (Elements, error)
- func (p *Page) ElementsE(objectID proto.RuntimeRemoteObjectID, selector string) (Elements, error)
- func (p *Page) ElementsX(xpath string) Elements
- func (p *Page) ElementsXE(objectID proto.RuntimeRemoteObjectID, xpath string) (Elements, error)
- func (p *Page) Emulate(device devices.DeviceType) *Page
- func (p *Page) EmulateE(device devices.DeviceType, landscape bool) error
- func (p *Page) EnableDomain(method proto.Payload) (recover func())
- func (p *Page) Eval(js string, params ...interface{}) proto.JSON
- func (p *Page) EvalE(byValue bool, thisID proto.RuntimeRemoteObjectID, js string, jsArgs Array) (*proto.RuntimeRemoteObject, error)
- func (p *Page) EvalOnNewDocument(js string)
- func (p *Page) EvalOnNewDocumentE(js string) (proto.PageScriptIdentifier, error)
- func (p *Page) Expose(name string) (callback chan string, stop func())
- func (p *Page) ExposeE(name string) (callback chan string, stop func(), err error)
- func (p *Page) ExposeJSHelper() *Page
- func (p *Page) GetContext() context.Context
- func (p *Page) GetDownloadFile(pattern string) func() []byte
- func (p *Page) GetDownloadFileE(pattern string, resourceType proto.NetworkResourceType) func() (http.Header, io.Reader, error)
- func (p *Page) GetWindow() *proto.BrowserBounds
- func (p *Page) GetWindowE() (*proto.BrowserBounds, error)
- func (p *Page) HandleDialog(accept bool, promptText string) (wait func())
- func (p *Page) HandleDialogE(accept bool, promptText string) func() error
- func (p *Page) Has(selector string) bool
- func (p *Page) HasE(selectors ...string) (bool, error)
- func (p *Page) HasMatches(selector, regex string) bool
- func (p *Page) HasMatchesE(pairs ...string) (bool, error)
- func (p *Page) HasX(selector string) bool
- func (p *Page) HasXE(selectors ...string) (bool, error)
- func (p *Page) HijackRequests() *HijackRouter
- func (p *Page) Info() *proto.TargetTargetInfo
- func (p *Page) InfoE() (*proto.TargetTargetInfo, error)
- func (p *Page) IsIframe() bool
- func (p *Page) LoadState(method proto.Payload) (has bool)
- func (p *Page) Navigate(url string) *Page
- func (p *Page) NavigateE(url string) error
- func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) proto.JSON
- func (p *Page) ObjectToJSONE(obj *proto.RuntimeRemoteObject) (proto.JSON, error)
- func (p *Page) ObjectsToJSON(list []*proto.RuntimeRemoteObject) proto.JSON
- func (p *Page) Overlay(left, top, width, height float64, msg string) (remove func())
- func (p *Page) PDF() []byte
- func (p *Page) PDFE(req *proto.PagePrintToPDF) ([]byte, error)
- func (p *Page) Pause() *Page
- func (p *Page) PauseE() error
- func (p *Page) Release(objectID proto.RuntimeRemoteObjectID) *Page
- func (p *Page) ReleaseE(objectID proto.RuntimeRemoteObjectID) error
- func (p *Page) Root() *Page
- func (p *Page) Screenshot(toFile ...string) []byte
- func (p *Page) ScreenshotE(fullpage bool, req *proto.PageCaptureScreenshot) ([]byte, error)
- func (p *Page) ScreenshotFullPage(toFile ...string) []byte
- func (p *Page) Search(queries ...string) *Element
- func (p *Page) SearchE(sleeper kit.Sleeper, queries []string, from, to int) (Elements, error)
- func (p *Page) SetCookies(cookies ...*proto.NetworkCookieParam) *Page
- func (p *Page) SetCookiesE(cookies []*proto.NetworkCookieParam) error
- func (p *Page) SetExtraHeaders(dict ...string) (cleanup func())
- func (p *Page) SetExtraHeadersE(dict []string) (func(), error)
- func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) *Page
- func (p *Page) SetUserAgentE(req *proto.NetworkSetUserAgentOverride) error
- func (p *Page) StopLoading() *Page
- func (p *Page) StopLoadingE() error
- func (p *Page) Timeout(d time.Duration) *Page
- func (p *Page) Viewport(width, height int64, deviceScaleFactor float64, mobile bool) *Page
- func (p *Page) ViewportE(params *proto.EmulationSetDeviceMetricsOverride) error
- func (p *Page) Wait(js string, params ...interface{})
- func (p *Page) WaitE(sleeper kit.Sleeper, thisID proto.RuntimeRemoteObjectID, js string, ...) error
- func (p *Page) WaitEvent(e proto.Payload) (wait func())
- func (p *Page) WaitIdle() *Page
- func (p *Page) WaitIdleE(timeout time.Duration) (err error)
- func (p *Page) WaitLoad() *Page
- func (p *Page) WaitLoadE() error
- func (p *Page) WaitOpen() (wait func() (newPage *Page))
- func (p *Page) WaitOpenE() func() (*Page, error)
- func (p *Page) WaitRequestIdle(excludes ...string) (wait func())
- func (p *Page) WaitRequestIdleE(d time.Duration, includes, excludes []string) func()
- func (p *Page) Window(left, top, width, height int64) *Page
- func (p *Page) WindowE(bounds *proto.BrowserBounds) error
- func (p *Page) WindowFullscreen() *Page
- func (p *Page) WindowMaximize() *Page
- func (p *Page) WindowMinimize() *Page
- func (p *Page) WindowNormal() *Page
- type Pages
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrValue error ErrValue = errors.New("[rod] error value") // ErrExpectElement error ErrExpectElement = errors.New("[rod] expect js to return an element") // ErrExpectElements error ErrExpectElements = errors.New("[rod] expect js to return an array of elements") // ErrElementNotFound error ErrElementNotFound = errors.New("[rod] cannot find element") // ErrWaitJSTimeout error ErrWaitJSTimeout = errors.New("[rod] wait js timeout") // ErrSrcNotFound error ErrSrcNotFound = errors.New("[rod] element doesn't have src attribute") // ErrEval error ErrEval = errors.New("[rod] eval error") ErrNavigation = errors.New("[rod] navigation failed") // ErrNotClickable error ErrNotClickable = errors.New("[rod] element is not clickable") )
var Sleeper = func() kit.Sleeper { return kit.BackoffSleeper(100*time.Millisecond, time.Second, nil) }
Sleeper returns the default sleeper for retry, it uses backoff to grow the interval. The growth looks like: A(0) = 100ms, A(n) = A(n-1) * random[1.9, 2.1), A(n) < 1s
Functions ¶
func Event ¶
Event helps to convert a cdp.Event to proto.Payload. Returns false if the conversion fails
func SprintFnThis ¶
SprintFnThis wrap js with this, wrap function call if it's js expression
Types ¶
type Array ¶
type Array []interface{}
Array of any type
func ArrayFromList ¶ added in v0.45.0
func ArrayFromList(list interface{}) Array
ArrayFromList converts a random list into Array type
type Browser ¶
type Browser struct { // BrowserContextID is the id for incognito window BrowserContextID proto.BrowserBrowserContextID // contains filtered or unexported fields }
Browser represents the browser It doesn't depends on file system, it should work with remote browser seamlessly. To check the env var you can use to quickly enable options from CLI, check here: https://pkg.go.dev/github.com/go-rod/rod/lib/defaults
func (*Browser) Call ¶
func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params json.RawMessage) (res []byte, err error)
Call raw cdp interface directly
func (*Browser) CallContext ¶
CallContext parameters for proto
func (*Browser) Connect ¶
Connect to the browser and start to control it. If fails to connect, try to run a local browser, if local browser not found try to download one.
func (*Browser) ControlURL ¶
ControlURL set the url to remote control browser.
func (*Browser) DisableDomain ¶
func (b *Browser) DisableDomain(ctx context.Context, sessionID proto.TargetSessionID, method proto.Payload) (recover func())
DisableDomain and returns a recover function to restore previous state
func (*Browser) EachEvent ¶
func (b *Browser) EachEvent(fn interface{}) (wait func())
EachEvent of the specified event type, if the fn returns true the event loop will stop. The fn can accpet multiple events, such as EachEvent(func(e1 *proto.PageLoadEventFired, e2 *proto.PageLifecycleEvent) {}), only one argument will be non-null, others will null.
func (*Browser) EnableDomain ¶
func (b *Browser) EnableDomain(ctx context.Context, sessionID proto.TargetSessionID, method proto.Payload) (recover func())
EnableDomain and returns a recover function to restore previous state
func (*Browser) Event ¶
func (b *Browser) Event() *goob.Observable
Event returns the observable for browser events
func (*Browser) GetContext ¶
GetContext returns the current context
func (*Browser) HandleAuth ¶
HandleAuth for the next basic HTTP authentication. It will prevent the popup that requires user to input user name and password. Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
func (*Browser) HandleAuthE ¶
HandleAuthE for the next basic HTTP authentication. It will prevent the popup that requires user to input user name and password. Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
func (*Browser) HijackRequests ¶
func (b *Browser) HijackRequests() *HijackRouter
HijackRequests creates a new router instance for requests hijacking. When use Fetch domain outside the router should be stopped. Enabling hijacking disables page caching, but such as 304 Not Modified will still work as expected.
func (*Browser) IncognitoE ¶
IncognitoE creates a new incognito browser
func (*Browser) Page ¶
Page creates a new tab If url is empty, the default target will be "about:blank".
func (*Browser) PageE ¶
PageE doc is similar to the method Page If url is empty, the default target will be "about:blank".
func (*Browser) PageFromTargetID ¶
func (b *Browser) PageFromTargetID(targetID proto.TargetTargetID) *Page
PageFromTargetID creates a Page instance from a targetID
func (*Browser) PageFromTargetIDE ¶
func (b *Browser) PageFromTargetIDE(targetID proto.TargetTargetID) (*Page, error)
PageFromTargetIDE creates a Page instance from a targetID
func (*Browser) Quiet ¶ added in v0.43.1
Quiet enables/disables log of the. Only useful when Trace is set to true.
func (*Browser) ServeMonitor ¶
func (b *Browser) ServeMonitor(host string, openBrowser bool) *kit.ServerContext
ServeMonitor starts the monitor server. If openBrowser is true, it will try to launcher a browser to play the screenshots. The reason why not to use "chrome://inspect/#devices" is one target cannot be driven by multiple controllers.
func (*Browser) Slowmotion ¶
Slowmotion set the delay for each control action, such as the simulation of the human inputs
type CDPCall ¶ added in v0.49.0
type CDPCall func(ctx context.Context, sessionID, method string, params interface{}) ([]byte, error)
CDPCall type for cdp.Client.CDPCall
type Element ¶
type Element struct { ObjectID proto.RuntimeRemoteObjectID // contains filtered or unexported fields }
Element represents the DOM element
func (*Element) Attribute ¶
Attribute returns the value of a specified attribute on the element. Please check the Property function before you use it, usually you don't want to use Attribute. https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html
func (*Element) AttributeE ¶
AttributeE is similar to the method Attribute
func (*Element) Blur ¶
Blur will call the blur function on the element. On inputs, this will deselect the element.
func (*Element) Box ¶
Box returns the size of an element and its position relative to the main frame.
func (*Element) BoxE ¶
BoxE returns the size of an element and its position relative to the main frame.
func (*Element) CallContext ¶
CallContext parameters for proto
func (*Element) CanvasToImage ¶ added in v0.45.1
CanvasToImage get image data of a canvas. The default format is image/png. The default quality is 0.92. doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
func (*Element) CanvasToImageE ¶ added in v0.45.1
CanvasToImageE get image data of a canvas. The default format is image/png. The default quality is 0.92. doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
func (*Element) ClickE ¶
func (el *Element) ClickE(button proto.InputMouseButton) error
ClickE will press then release the button just like a human.
func (*Element) Clickable ¶ added in v0.48.0
Clickable checks if the element is behind another element, such as when covered by a modal.
func (*Element) ClickableE ¶ added in v0.48.0
ClickableE checks if the element is behind another element, such as when invisible or covered by a modal.
func (*Element) ContainsElement ¶ added in v0.48.0
ContainsElement check if the target is equal or inside the element.
func (*Element) ContainsElementE ¶ added in v0.48.0
ContainsElementE check if the target is equal or inside the element.
func (*Element) Describe ¶
Describe returns the element info Returned json: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-Node
func (*Element) DescribeE ¶
DescribeE doc is similar to the method Describe please see https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-describeNode
func (*Element) ElementByJS ¶
ElementByJS returns the element from the return value of the js
func (*Element) ElementByJSE ¶
ElementByJSE doc is similar to the method ElementByJS
func (*Element) ElementMatches ¶
ElementMatches returns the first element in the page that matches the CSS selector and its text matches the regex. The regex is the js regex, not golang's.
func (*Element) ElementMatchesE ¶
ElementMatchesE doc is similar to the method ElementMatches
func (*Element) ElementsByJS ¶
ElementsByJS returns the elements from the return value of the js
func (*Element) ElementsByJSE ¶
ElementsByJSE doc is similar to the method ElementsByJS
func (*Element) ElementsXE ¶
ElementsXE doc is similar to the method ElementsX
func (*Element) Eval ¶
Eval evaluates js function on the element, the first param must be a js function definition For example: el.Eval(`name => this.getAttribute(name)`, "value")
func (*Element) GetContext ¶
GetContext returns the current context
func (*Element) HasMatches ¶
HasMatches an element that matches the css selector and its text matches the regex.
func (*Element) HasMatchesE ¶
HasMatchesE doc is similar to the method HasMatches
func (*Element) Input ¶
Input wll click the element and input the text. To empty the input you can use something like el.SelectAllText().Input("")
func (*Element) Matches ¶ added in v0.45.0
Matches checks if the element can be selected by the css selector
func (*Element) MatchesE ¶ added in v0.45.0
MatchesE checks if the element can be selected by the css selector
func (*Element) Property ¶
Property returns the value of a specified property on the element. It's similar to Attribute but attributes can only be string, properties can be types like bool, float, etc. https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html
func (*Element) Resource ¶
Resource returns the binary of the "src" properly, such as the image or audio file.
func (*Element) Screenshot ¶
Screenshot of the area of the element
func (*Element) ScreenshotE ¶
func (el *Element) ScreenshotE(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error)
ScreenshotE of the area of the element
func (*Element) ScrollIntoView ¶
ScrollIntoView scrolls the current element into the visible area of the browser window if it's not already within the visible area.
func (*Element) ScrollIntoViewE ¶
ScrollIntoViewE doc is similar to the method ScrollIntoViewIfNeeded
func (*Element) Select ¶
Select the option elements that match the selectors, the selector can be text content or css selector
func (*Element) SelectAllText ¶
SelectAllText selects all text
func (*Element) SelectAllTextE ¶
SelectAllTextE doc is similar to the method SelectAllText
func (*Element) SelectText ¶
SelectText selects the text that matches the regular expression
func (*Element) SelectTextE ¶
SelectTextE doc is similar to the method SelectText
func (*Element) ShadowRoot ¶
ShadowRoot returns the shadow root of this element
func (*Element) ShadowRootE ¶
ShadowRootE returns the shadow root of this element
func (*Element) WaitInvisible ¶
WaitInvisible until the element is not visible or removed
func (*Element) WaitInvisibleE ¶
WaitInvisibleE doc is similar to the method WaitInvisible
func (*Element) WaitStable ¶
WaitStable waits until the size and position are stable. Useful when waiting for the animation of modal or button to complete so that we can simulate the mouse to move to it and click on it.
func (*Element) WaitStableE ¶
WaitStableE not using requestAnimation here because it can trigger to many checks, or miss checks for jQuery css animation.
func (*Element) WaitVisible ¶
WaitVisible until the element is visible
func (*Element) WaitVisibleE ¶
WaitVisibleE doc is similar to the method WaitVisible
type Elements ¶
type Elements []*Element
Elements provides some helpers to deal with element list
type Hijack ¶
type Hijack struct { Request *HijackRequest Response *HijackResponse OnError func(error) // Skip to next handler Skip bool // contains filtered or unexported fields }
Hijack context
func (*Hijack) ContinueRequest ¶ added in v0.42.0
func (h *Hijack) ContinueRequest(cq *proto.FetchContinueRequest)
ContinueRequest without hijacking
func (*Hijack) LoadResponse ¶
func (h *Hijack) LoadResponse()
LoadResponse will send request to the real destination and load the response as default response to override.
func (*Hijack) LoadResponseE ¶
LoadResponseE will send request to the real destination and load the response as default response to override.
type HijackRequest ¶
type HijackRequest struct {
// contains filtered or unexported fields
}
HijackRequest context
func (*HijackRequest) Body ¶
func (ctx *HijackRequest) Body() string
Body of the request, devtools API doesn't support binary data yet, only string can be captured.
func (*HijackRequest) Headers ¶
func (ctx *HijackRequest) Headers() proto.NetworkHeaders
Headers of request
func (*HijackRequest) JSONBody ¶
func (ctx *HijackRequest) JSONBody() gjson.Result
JSONBody of the request
func (*HijackRequest) SetBody ¶
func (ctx *HijackRequest) SetBody(obj interface{}) *HijackRequest
SetBody of the request, if obj is []byte or string, raw body will be used, else it will be encoded as json.
func (*HijackRequest) SetClient ¶ added in v0.41.0
func (ctx *HijackRequest) SetClient(client *http.Client) *HijackRequest
SetClient for http
func (*HijackRequest) SetHeader ¶
func (ctx *HijackRequest) SetHeader(pairs ...string) *HijackRequest
SetHeader via key-value pairs
func (*HijackRequest) SetMethod ¶
func (ctx *HijackRequest) SetMethod(name string) *HijackRequest
SetMethod of request
func (*HijackRequest) SetQuery ¶
func (ctx *HijackRequest) SetQuery(pairs ...interface{}) *HijackRequest
SetQuery of the request, example Query(k, v, k, v ...)
func (*HijackRequest) SetURL ¶
func (ctx *HijackRequest) SetURL(url string) *HijackRequest
SetURL of the request
func (*HijackRequest) Type ¶ added in v0.49.1
func (ctx *HijackRequest) Type() proto.NetworkResourceType
Type of the resource
type HijackResponse ¶
type HijackResponse struct {
// contains filtered or unexported fields
}
HijackResponse context
func (*HijackResponse) BodyStream ¶ added in v0.42.0
func (ctx *HijackResponse) BodyStream() io.Reader
BodyStream returns the stream of the body
func (*HijackResponse) BodyStreamE ¶ added in v0.42.0
func (ctx *HijackResponse) BodyStreamE() (io.Reader, error)
BodyStreamE returns the stream of the body
func (*HijackResponse) Fail ¶ added in v0.48.1
func (ctx *HijackResponse) Fail(reason proto.NetworkErrorReason) *HijackResponse
Fail request
func (*HijackResponse) HeaderE ¶
func (ctx *HijackResponse) HeaderE(key string) (string, error)
HeaderE via key
func (*HijackResponse) Headers ¶
func (ctx *HijackResponse) Headers() http.Header
Headers of request
func (*HijackResponse) HeadersE ¶
func (ctx *HijackResponse) HeadersE() (http.Header, error)
HeadersE of request
func (*HijackResponse) JSONBody ¶
func (ctx *HijackResponse) JSONBody() gjson.Result
JSONBody of response
func (*HijackResponse) SetBody ¶
func (ctx *HijackResponse) SetBody(obj interface{}) *HijackResponse
SetBody of response, if obj is []byte, raw body will be used, else it will be encoded as json
func (*HijackResponse) SetHeader ¶
func (ctx *HijackResponse) SetHeader(pairs ...string)
SetHeader via key-value pairs
func (*HijackResponse) SetStatusCode ¶
func (ctx *HijackResponse) SetStatusCode(code int)
SetStatusCode of response
func (*HijackResponse) StatusCode ¶
func (ctx *HijackResponse) StatusCode() int
StatusCode of response
func (*HijackResponse) StatusCodeE ¶
func (ctx *HijackResponse) StatusCodeE() (int, error)
StatusCodeE of response
func (*HijackResponse) StringBody ¶
func (ctx *HijackResponse) StringBody() string
StringBody of response
type HijackRouter ¶
type HijackRouter struct {
// contains filtered or unexported fields
}
HijackRouter context
func (*HijackRouter) Add ¶
func (r *HijackRouter) Add(pattern string, handler func(*Hijack))
Add a hijack handler to router, the doc of the pattern is the same as "proto.FetchRequestPattern.URLPattern". You can add new handler even after the "Run" is called.
func (*HijackRouter) AddE ¶
func (r *HijackRouter) AddE(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error
AddE a hijack handler to router, the doc of the pattern is the same as "proto.FetchRequestPattern.URLPattern". You can add new handler even after the "Run" is called.
func (*HijackRouter) Remove ¶
func (r *HijackRouter) Remove(pattern string)
Remove handler via the pattern
func (*HijackRouter) RemoveE ¶
func (r *HijackRouter) RemoveE(pattern string) error
RemoveE handler via the pattern
func (*HijackRouter) Run ¶
func (r *HijackRouter) Run()
Run the router, after you call it, you shouldn't add new handler to it.
type Keyboard ¶
type Keyboard struct {
// contains filtered or unexported fields
}
Keyboard represents the keyboard on a page, it's always related the main frame
func (*Keyboard) InsertText ¶
InsertText like paste text into the page
func (*Keyboard) InsertTextE ¶
InsertTextE doc is similar to the method InsertText
type Mouse ¶
type Mouse struct {
// contains filtered or unexported fields
}
Mouse represents the mouse on a page, it's always related the main frame
func (*Mouse) Click ¶
func (m *Mouse) Click(button proto.InputMouseButton) *Mouse
Click will press then release the button
func (*Mouse) ClickE ¶
func (m *Mouse) ClickE(button proto.InputMouseButton) error
ClickE doc is similar to the method Click
func (*Mouse) Down ¶
func (m *Mouse) Down(button proto.InputMouseButton) *Mouse
Down holds the button down
func (*Mouse) DownE ¶
func (m *Mouse) DownE(button proto.InputMouseButton, clicks int64) error
DownE doc is similar to the method Down
type Page ¶
type Page struct { TargetID proto.TargetTargetID SessionID proto.TargetSessionID // devices Mouse *Mouse Keyboard *Keyboard // contains filtered or unexported fields }
Page represents the webpage We try to hold as less states as possible
func (*Page) AddScriptTag ¶
AddScriptTag to page. If url is empty, content will be used.
func (*Page) AddScriptTagE ¶
AddScriptTagE to page. If url is empty, content will be used.
func (*Page) AddStyleTag ¶
AddStyleTag to page. If url is empty, content will be used.
func (*Page) AddStyleTagE ¶
AddStyleTagE to page. If url is empty, content will be used.
func (*Page) CallContext ¶
CallContext parameters for proto
func (*Page) Cookies ¶
func (p *Page) Cookies(urls ...string) []*proto.NetworkCookie
Cookies returns the page cookies. By default it will return the cookies for current page. The urls is the list of URLs for which applicable cookies will be fetched.
func (*Page) CookiesE ¶
func (p *Page) CookiesE(urls []string) ([]*proto.NetworkCookie, error)
CookiesE returns the page cookies. By default it will return the cookies for current page. The urls is the list of URLs for which applicable cookies will be fetched.
func (*Page) DisableDomain ¶
DisableDomain and returns a recover function to restore previous state
func (*Page) EachEvent ¶
func (p *Page) EachEvent(fn interface{}) (wait func())
EachEvent of the specified event type, if the fn returns true the event loop will stop. The fn can accpet multiple events, such as EachEventE(func(e1 *proto.PageLoadEventFired, e2 *proto.PageLifecycleEvent) {}), only one argument will be non-null, others will null.
func (*Page) Element ¶
Element retries until an element in the page that matches one of the CSS selectors
func (*Page) ElementByJS ¶
ElementByJS retries until returns the element from the return value of the js function
func (*Page) ElementByJSE ¶
func (p *Page) ElementByJSE(sleeper kit.Sleeper, thisID proto.RuntimeRemoteObjectID, js string, params Array) (*Element, error)
ElementByJSE returns the element from the return value of the js function. sleeper is used to sleep before retry the operation. If sleeper is nil, no retry will be performed. thisID is the this value of the js function, when thisID is "", the this context will be the "window". If the js function returns "null", ElementByJSE will retry, you can use custom sleeper to make it only retry once.
func (*Page) ElementE ¶
func (p *Page) ElementE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, selectors []string) (*Element, error)
ElementE finds element by css selector
func (*Page) ElementFromNode ¶ added in v0.47.0
ElementFromNode creates an Element from the node id
func (*Page) ElementFromNodeE ¶ added in v0.47.0
ElementFromNodeE creates an Element from the node id
func (*Page) ElementFromObject ¶ added in v0.47.0
func (p *Page) ElementFromObject(id proto.RuntimeRemoteObjectID) *Element
ElementFromObject creates an Element from the remote object id.
func (*Page) ElementFromPoint ¶ added in v0.48.0
ElementFromPoint creates an Element from the absolute point on the page. The point should include the window scroll offset.
func (*Page) ElementFromPointE ¶ added in v0.48.0
ElementFromPointE creates an Element from the absolute point on the page. The point should include the window scroll offset.
func (*Page) ElementMatches ¶
ElementMatches retries until an element in the page that matches one of the pairs. Each pairs is a css selector and a regex. A sample call will look like page.ElementMatches("div", "click me"). The regex is the js regex, not golang's.
func (*Page) ElementMatchesE ¶
func (p *Page) ElementMatchesE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, pairs []string) (*Element, error)
ElementMatchesE doc is similar to the method ElementMatches
func (*Page) ElementX ¶
ElementX retries until an element in the page that matches one of the XPath selectors
func (*Page) ElementXE ¶
func (p *Page) ElementXE(sleeper kit.Sleeper, objectID proto.RuntimeRemoteObjectID, xPaths []string) (*Element, error)
ElementXE finds elements by XPath
func (*Page) ElementsByJS ¶
ElementsByJS returns the elements from the return value of the js
func (*Page) ElementsByJSE ¶
func (p *Page) ElementsByJSE(thisID proto.RuntimeRemoteObjectID, js string, params Array) (Elements, error)
ElementsByJSE is different from ElementByJSE, it doesn't do retry
func (*Page) ElementsXE ¶
ElementsXE doc is similar to the method ElementsX
func (*Page) Emulate ¶ added in v0.42.1
func (p *Page) Emulate(device devices.DeviceType) *Page
Emulate the device, such as iPhone9. If device is empty, it will clear the override.
func (*Page) EmulateE ¶ added in v0.42.1
func (p *Page) EmulateE(device devices.DeviceType, landscape bool) error
EmulateE the device, such as iPhone9. If device is empty, it will clear the override.
func (*Page) EnableDomain ¶
EnableDomain and returns a recover function to restore previous state
func (*Page) Eval ¶
Eval js on the page. The first param must be a js function definition. For example page.Eval(`n => n + 1`, 1) will return 2
func (*Page) EvalE ¶
func (p *Page) EvalE(byValue bool, thisID proto.RuntimeRemoteObjectID, js string, jsArgs Array) (*proto.RuntimeRemoteObject, error)
EvalE thisID is the remote objectID that will be the this of the js function, if it's empty "window" will be used. Set the byValue to true to reduce memory occupation. If the item in jsArgs is proto.RuntimeRemoteObjectID, the remote object will be used, else the item will be treated as JSON value.
func (*Page) EvalOnNewDocument ¶ added in v0.44.0
EvalOnNewDocument Evaluates given script in every frame upon creation (before loading frame's scripts).
func (*Page) EvalOnNewDocumentE ¶ added in v0.44.0
func (p *Page) EvalOnNewDocumentE(js string) (proto.PageScriptIdentifier, error)
EvalOnNewDocumentE Evaluates given script in every frame upon creation (before loading frame's scripts).
func (*Page) Expose ¶ added in v0.49.1
Expose function to the page's window object. Must bind before navigate to the page. Bindings survive reloads. Binding function takes exactly one argument, this argument should be string.
func (*Page) ExposeE ¶ added in v0.49.1
ExposeE function to the page's window object. Must bind before navigate to the page. Bindings survive reloads. Binding function takes exactly one argument, this argument should be string.
func (*Page) ExposeJSHelper ¶ added in v0.45.0
ExposeJSHelper to page's window object, so you can debug helper.js in the browser console. Such as run `rod.elementMatches("div", "ok")` in the browser console to test the Page.ElementMatches.
func (*Page) GetContext ¶
GetContext returns the current context
func (*Page) GetDownloadFile ¶
GetDownloadFile of the next download url that matches the pattern, returns the file content.
func (*Page) GetDownloadFileE ¶
func (p *Page) GetDownloadFileE(pattern string, resourceType proto.NetworkResourceType) func() (http.Header, io.Reader, error)
GetDownloadFileE of the next download url that matches the pattern, returns the file content. The handler will be used once and removed.
func (*Page) GetWindow ¶
func (p *Page) GetWindow() *proto.BrowserBounds
GetWindow get window bounds
func (*Page) GetWindowE ¶
func (p *Page) GetWindowE() (*proto.BrowserBounds, error)
GetWindowE doc is similar to the method GetWindow
func (*Page) HandleDialog ¶
HandleDialog accepts or dismisses next JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) Because alert will block js, usually you have to run the wait function inside a goroutine. Check the unit test for it for more information.
func (*Page) HandleDialogE ¶
HandleDialogE doc is similar to the method HandleDialog
func (*Page) HasMatches ¶
HasMatches an element that matches the css selector and its text matches the regex.
func (*Page) HasMatchesE ¶
HasMatchesE doc is similar to the method HasMatches
func (*Page) HijackRequests ¶
func (p *Page) HijackRequests() *HijackRouter
HijackRequests same as Browser.HijackRequests, but scoped with the page
func (*Page) Info ¶ added in v0.42.1
func (p *Page) Info() *proto.TargetTargetInfo
Info of the page, such as the URL or title of the page
func (*Page) InfoE ¶ added in v0.42.1
func (p *Page) InfoE() (*proto.TargetTargetInfo, error)
InfoE of the page, such as the URL or title of the page
func (*Page) NavigateE ¶
NavigateE doc is similar to the method Navigate If url is empty, it will navigate to "about:blank".
func (*Page) ObjectToJSON ¶
func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) proto.JSON
ObjectToJSON by remote object
func (*Page) ObjectToJSONE ¶
ObjectToJSONE by object id
func (*Page) ObjectsToJSON ¶
func (p *Page) ObjectsToJSON(list []*proto.RuntimeRemoteObject) proto.JSON
ObjectsToJSON by remote objects
func (*Page) PDFE ¶
func (p *Page) PDFE(req *proto.PagePrintToPDF) ([]byte, error)
PDFE prints page as PDF
func (*Page) Release ¶
func (p *Page) Release(objectID proto.RuntimeRemoteObjectID) *Page
Release remote object
func (*Page) ReleaseE ¶
func (p *Page) ReleaseE(objectID proto.RuntimeRemoteObjectID) error
ReleaseE doc is similar to the method Release
func (*Page) Screenshot ¶
Screenshot the page and returns the binary of the image If the toFile is "", it will save output to "tmp/screenshots" folder, time as the file name.
func (*Page) ScreenshotE ¶
ScreenshotE options: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureScreenshot
func (*Page) ScreenshotFullPage ¶
ScreenshotFullPage including all scrollable content and returns the binary of the image.
func (*Page) Search ¶ added in v0.47.0
Search for each given query in the DOM tree until find one, before that it will keep retrying. The query can be plain text or css selector or xpath. It will search nested iframes and shadow doms too.
func (*Page) SearchE ¶ added in v0.47.0
SearchE for each given query in the DOM tree until the result count is not zero, before that it will keep retrying. The query can be plain text or css selector or xpath. It will search nested iframes and shadow doms too.
func (*Page) SetCookies ¶
func (p *Page) SetCookies(cookies ...*proto.NetworkCookieParam) *Page
SetCookies of the page. Cookie format: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie
func (*Page) SetCookiesE ¶
func (p *Page) SetCookiesE(cookies []*proto.NetworkCookieParam) error
SetCookiesE of the page. Cookie format: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie
func (*Page) SetExtraHeaders ¶
SetExtraHeaders whether to always send extra HTTP headers with the requests from this page. The arguments are key-value pairs, you can set multiple key-value pairs at the same time.
func (*Page) SetExtraHeadersE ¶
SetExtraHeadersE whether to always send extra HTTP headers with the requests from this page.
func (*Page) SetUserAgent ¶
func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) *Page
SetUserAgent Allows overriding user agent with the given string. If req is nil, the default user agent will be the same as a mac chrome.
func (*Page) SetUserAgentE ¶
func (p *Page) SetUserAgentE(req *proto.NetworkSetUserAgentOverride) error
SetUserAgentE Allows overriding user agent with the given string. If req is nil, the default user agent will be the same as a mac chrome.
func (*Page) StopLoading ¶
StopLoading forces the page stop all navigations and pending resource fetches.
func (*Page) StopLoadingE ¶
StopLoadingE forces the page stop navigation and pending resource fetches.
func (*Page) ViewportE ¶
func (p *Page) ViewportE(params *proto.EmulationSetDeviceMetricsOverride) error
ViewportE doc is similar to the method Viewport. If params is nil, it will clear the override.
func (*Page) WaitE ¶
func (p *Page) WaitE(sleeper kit.Sleeper, thisID proto.RuntimeRemoteObjectID, js string, params Array) error
WaitE js function until it returns true
func (*Page) WaitEvent ¶
WaitEvent waits for the next event for one time. It will also load the data into the event object.
func (*Page) WaitLoad ¶
WaitLoad wait until the `window.onload` is complete, resolve immediately if already fired.
func (*Page) WaitRequestIdle ¶
WaitRequestIdle returns a wait function that waits until the page doesn't send request for 300ms. You can pass regular expressions to exclude the requests by their url.
func (*Page) WaitRequestIdleE ¶
WaitRequestIdleE returns a wait function that waits until no request for d duration. Use the includes and excludes regexp list to filter the requests by their url. Such as set n to 1 if there's a polling request.
func (*Page) WindowE ¶
func (p *Page) WindowE(bounds *proto.BrowserBounds) error
WindowE https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-Bounds
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
fixtures
|
|
lib
|
|
defaults
Package defaults holds some commonly used options parsed from env var "rod".
|
Package defaults holds some commonly used options parsed from env var "rod". |
examples/custom-websocket
Module
|
|
utils/check-issue
Module
|