rod

package module
v0.108.3-0...-9e82425 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2022 License: MIT Imports: 34 Imported by: 0

README

概览

Go Reference Discord Chat

教程文档 | 英文 API 参考文档 | 中文 API 参考文档 | 项目管理 | FAQ

Rod 是一个直接基于 DevTools Protocol 高级驱动程序。 它是为网页自动化和爬虫而设计的,既可用于高级应用开发也可用于低级应用开发,高级开发人员可以使用低级包和函数来轻松地定制或建立他们自己的Rod版本,高级函数只是建立Rod默认版本的例子。

特性

  • 链式上下文设计,直观地超时或取消长时间运行的任务
  • 自动等待元素准备就绪
  • 调试友好,自动输入跟踪,远程监控无头浏览器
  • 所有操作都是线程安全的
  • 自动查找或下载 浏览器
  • 高级的辅助程序像 WaitStable, WaitRequestIdle, HijackRequests, WaitDownload,等
  • 两步式的 WaitEvent 设计,永远不会错过任何一个事件 (工作原理)
  • 正确地处理嵌套的iframe或影子DOM
  • 崩溃后没有僵尸浏览器进程 (工作原理)
  • CI 100% 的测试覆盖率

关于中文 API 参考文档的说明

  • 中文 API 参考文档中含有 TODO 的地方,表示目前的没有较好的翻译,如果有觉得很适合的翻译,请在中文仓库下提交 issues/discussions
  • 翻译风格,翻译建议,翻译勘误,请在中文仓库下提交 issues/discussions
  • 不建议将中文仓库的代码,使用在您的项目中,强烈建议使用英文仓库的代码。中文仓库仅供作为 API 文档中文版的参考
  • 关于API文档的翻译情况:对于底层库封装出来的接口已经全部翻译,底层库目前仅翻译了一些和功能业务相关的,例如:Network,Page等
  • 欢迎加入 rod 中文 API 参考文档的建设当中来

示例

首先请查看 examples_test.go, 然后查看 examples 文件夹.有关更详细的示例,请搜索单元测试。 例如 HandleAuth的使用, 你可以搜索所有 *_test.go 文件包含HandleAuth的,例如,使用 Github 在线搜索 在仓库中搜索。 你也可以搜索 GitHub 的 issues 或者 discussions,这里记录了更多的使用示例。

这里 是一个 rod 和 chromedp 的比较。

如果你有疑问,可以提 issues/discussions 或者加入 chat room

加入我们

我们非常欢迎你的帮助! 即使只是打开一个问题,提出一个问题,也可能大大帮助别人。

在你提出问题之前,请阅读 如何聪明的提问

我们使用 Github 项目来管理任务,你可以在这里看到这些问题的优先级和进展。

如果你想为项目作出贡献,请阅读 Contributor Guide

Documentation

Overview

This file defines the helpers to develop automation. 这个文件定义了一些开发自动化的辅助工具 Such as when running automation we can use trace to visually see where the mouse going to click. 如在运行自动化时,我们可以用trace(跟踪)来直观地看到鼠标要点击的地方。

Example

This example opens https://github.com/, searches for "git", and then gets the header element which gives the description for Git.

package main

import (
	"fmt"

	"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().MustConnect()

	// Even you forget to close, rod will close it after main process ends.
	defer browser.MustClose()

	// Create a new page
	page := browser.MustPage("https://github.com")

	// We use css selector to get the search input element and input "git"
	page.MustElement("input").MustInput("git").MustType(input.Enter)

	// Wait until css selector get the element then get the text content of it.
	text := page.MustElement(".codesearch-results p").MustText()

	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("Found", len(page.MustElements("input")), "input elements")

	// Eval js on the page
	page.MustEval(`() => console.log("hello world")`)

	// Pass parameters as json objects to the js function. This MustEval will result 3
	fmt.Println("1 + 2 =", page.MustEval(`(a, b) => a + b`, 1, 2).Int())

	// When eval on an element, "this" in the js is the current DOM element.
	fmt.Println(page.MustElement("title").MustEval(`() => this.innerText`).String())

}
Output:

Git is the most widely used version control system.
Found 5 input elements
1 + 2 = 3
Search · git · GitHub
Example (Context_and_timeout)

Rod use https://golang.org/pkg/context to handle cancelations for IO blocking operations, most times it's timeout. Context will be recursively passed to all sub-methods. For example, methods like Page.Context(ctx) will return a clone of the page with the ctx, all the methods of the returned page will use the ctx if they have IO blocking operations. Page.Timeout or Page.WithCancel is just a shortcut for Page.Context. Of course, Browser or Element works the same way.

package main

import (
	"math/rand"
	"time"

	"github.com/go-rod/rod"
)

func main() {
	page := rod.New().MustConnect().MustPage("https://github.com")

	page.
		// Set a 5-second timeout for all chained methods
		Timeout(5 * time.Second).

		// The total time for MustWaitLoad and MustElement must be less than 5 seconds
		MustWaitLoad().
		MustElement("title").

		// Methods after CancelTimeout won't be affected by the 5-second timeout
		CancelTimeout().

		// Set a 10-second timeout for all chained methods
		Timeout(10 * time.Second).

		// Panics if it takes more than 10 seconds
		MustText()

	// The two code blocks below are basically the same:
	{
		page.Timeout(5 * time.Second).MustElement("a").CancelTimeout()
	}
	{
		// Use this way you can customize your own way to cancel long-running task
		page, cancel := page.WithCancel()
		go func() {
			time.Sleep(time.Duration(rand.Int())) // cancel after randomly time
			cancel()
		}()
		page.MustElement("a")
	}
}
Output:

Example (Customize_browser_launch)

Shows how we can further customize the browser with the launcher library. Usually you use launcher lib to set the browser's command line flags (switches). Doc for flags: https://peter.sh/experiments/chromium-command-line-switches

package main

import (
	"fmt"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
)

func main() {
	url := launcher.New().
		Proxy("127.0.0.1:8080").     // set flag "--proxy-server=127.0.0.1:8080"
		Delete("use-mock-keychain"). // delete flag "--use-mock-keychain"
		MustLaunch()

	browser := rod.New().ControlURL(url).MustConnect()
	defer browser.MustClose()

	// So that we don't have to self issue certs for MITM
	browser.MustIgnoreCertErrors(true)

	// Adding authentication to the proxy, for the next auth request.
	// We use CLI tool "mitmproxy --proxyauth user:pass" as an example.
	go browser.MustHandleAuth("user", "pass")()

	// mitmproxy needs a cert config to support https. We use http here instead,
	// for example
	fmt.Println(browser.MustPage("https://mdn.dev/").MustElement("title").MustText())
}
Output:

Example (Customize_retry_strategy)

Shows how 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"
	"github.com/go-rod/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://github.com")

	// sleep for 0.5 seconds before every retry
	sleeper := func() utils.Sleeper {
		return func(context.Context) error {
			time.Sleep(time.Second / 2)
			return nil
		}
	}
	el, _ := page.Sleeper(sleeper).Element("input")
	fmt.Println(el.MustProperty("name"))

	// If sleeper is nil page.ElementE will query without retrying.
	// If nothing found it will return an error.
	el, err := page.Sleeper(rod.NotFoundSleeper).Element("input")
	if errors.Is(err, &rod.ErrElementNotFound{}) {
		fmt.Println("element not found")
	} else if err != nil {
		panic(err)
	}

	fmt.Println(el.MustProperty("name"))

}
Output:

q
q
Example (Direct_cdp)

When rod doesn't have a feature that you need. You can easily call the cdp to achieve it. List of cdp API: https://github.com/go-rod/rod/tree/master/lib/proto

package main

import (
	"context"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/proto"
)

func main() {
	page := rod.New().MustConnect().MustPage()

	// Rod doesn't have a method to enable AD blocking,
	// but you can call cdp interface directly to achieve it.

	// The two code blocks below are equal to enable AD blocking

	{
		_ = proto.PageSetAdBlockingEnabled{
			Enabled: true,
		}.Call(page)
	}

	{
		// Interact with the cdp JSON API directly
		_, _ = page.Call(context.TODO(), "", "Page.setAdBlockingEnabled", map[string]bool{
			"enabled": true,
		})
	}
}
Output:

Example (Disable_headless_to_debug)

Shows how to disable headless mode and debug. Rod provides a lot of debug options, you can set them with setter methods or use environment variables. Doc for environment variables: https://pkg.go.dev/github.com/go-rod/rod/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"
	"github.com/go-rod/rod/lib/utils"
)

func main() {
	// Headless runs the browser on foreground, you can also use flag "-rod=show"
	// Devtools opens the tab in each new tab opened automatically
	l := launcher.New().
		Headless(false).
		Devtools(true)

	defer l.Cleanup() // remove launcher.FlagUserDataDir

	url := l.MustLaunch()

	// 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().
		ControlURL(url).
		Trace(true).
		SlowMotion(2 * time.Second).
		MustConnect()

	// ServeMonitor plays screenshots of each tab. This feature is extremely
	// useful when debugging with headless mode.
	// You can also enable it with flag "-rod=monitor"
	launcher.Open(browser.ServeMonitor(""))

	defer browser.MustClose()

	page := browser.MustPage("https://github.com/")

	page.MustElement("input").MustInput("git").MustType(input.Enter)

	text := page.MustElement(".codesearch-results p").MustText()

	fmt.Println(text)

	utils.Pause() // pause goroutine
}
Output:

Example (Download_file)
package main

import (
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	page := browser.MustPage("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/")

	wait := browser.MustWaitDownload()

	page.MustElementR("a", "DOWNLOAD SAMPLE PDF FILE").MustClick()

	_ = utils.OutputFile("t.pdf", wait())
}
Output:

Example (Error_handling)

We use "Must" prefixed functions to write example code. But in production you may want to use the no-prefix version of them. About why we use "Must" as the prefix, it's similar to https://golang.org/pkg/regexp/#MustCompile

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/go-rod/rod"
)

func main() {
	page := rod.New().MustConnect().MustPage("https://mdn.dev")

	// We use Go's standard way to check error types, no magic.
	check := func(err error) {
		var evalErr *rod.ErrEval
		if errors.Is(err, context.DeadlineExceeded) { // timeout error
			fmt.Println("timeout err")
		} else if errors.As(err, &evalErr) { // eval error
			fmt.Println(evalErr.LineNumber)
		} else if err != nil {
			fmt.Println("can't handle", err)
		}
	}

	// The two code blocks below are doing the same thing in two styles:

	// The block below is better for debugging or quick scripting. We use panic to short-circuit logics.
	// So that we can take advantage of fluent interface (https://en.wikipedia.org/wiki/Fluent_interface)
	// and fail-fast (https://en.wikipedia.org/wiki/Fail-fast).
	// This style will reduce code, but it may also catch extra errors (less consistent and precise).
	{
		err := rod.Try(func() {
			fmt.Println(page.MustElement("a").MustHTML()) // use "Must" prefixed functions
		})
		check(err)
	}

	// The block below is better for production code. It's the standard way to handle errors.
	// Usually, this style is more consistent and precise.
	{
		el, err := page.Element("a")
		if err != nil {
			check(err)
			return
		}
		html, err := el.HTML()
		if err != nil {
			check(err)
			return
		}
		fmt.Println(html)
	}
}
Output:

Example (Eval_reuse_remote_object)

Shows how to share a remote object reference between two Eval

package main

import (
	"fmt"

	"github.com/go-rod/rod"
)

func main() {
	page := rod.New().MustConnect().MustPage()

	fn := page.MustEvaluate(rod.Eval(`() => Math.random`).ByObject())

	res := page.MustEval(`f => f()`, fn)

	// print a random number
	fmt.Println(res.Num())
}
Output:

Example (Handle_events)

Shows how to listen for events.

package main

import (
	"fmt"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/proto"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	done := make(chan struct{})

	// Listen for all events of console output.
	go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {
		fmt.Println(page.MustObjectsToJSON(e.Args))
		close(done)
	})()

	wait := page.WaitEvent(&proto.PageLoadEventFired{})
	page.MustNavigate("https://mdn.dev")
	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 to unsubscribe events.
		wait := page.EachEvent(func(e *proto.PageLoadEventFired) (stop bool) {
			return true
		})
		page.MustNavigate("https://mdn.dev")
		wait()
	}

	// Or the for-loop style to handle events to do the same thing above.
	if false {
		page.MustNavigate("https://mdn.dev")

		for msg := range page.Event() {
			e := proto.PageLoadEventFired{}
			if msg.Load(&e) {
				break
			}
		}
	}

	page.MustEval(`() => console.log("hello", "world")`)

	<-done

}
Output:

[hello world]
Example (Hijack_requests)

Shows how to intercept requests and modify both the request and the response. The entire process of hijacking one request:

browser --req-> rod ---> server ---> rod --res-> browser

The --req-> and --res-> are the parts that can be modified.

package main

import (
	"fmt"
	"net/http"

	"github.com/go-rod/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	router := browser.HijackRequests()
	defer router.MustStop()

	router.MustAdd("*.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.Req().Header.Set("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
		// ctx.Response struct.
		_ = ctx.LoadResponse(http.DefaultClient, true)

		// Here we append some code to every js file.
		// The code will update the document title to "hi"
		ctx.Response.SetBody(ctx.Response.Body() + "\n document.title = 'hi' ")
	})

	go router.Run()

	browser.MustPage("https://go-rod.github.io").MustWait(`() => document.title === 'hi'`)

	fmt.Println("done")

}
Output:

done
Example (Load_extension)
package main

import (
	"fmt"
	"path/filepath"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
)

func main() {
	extPath, _ := filepath.Abs("fixtures/chrome-extension")

	u := launcher.New().
		// Must use abs path for an extension
		Set("load-extension", extPath).
		// Headless mode doesn't support extension yet.
		// Reason: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c5
		// You can use XVFB to get rid of it: https://github.com/go-rod/rod/blob/master/lib/examples/launch-managed/main.go
		Headless(false).
		MustLaunch()

	page := rod.New().ControlURL(u).MustConnect().MustPage("http://mdn.dev")

	page.MustWait(`() => document.title === 'test-extension'`)

	fmt.Println("ok")

	// Skip
	
Output:

Example (Log_cdp_traffic)
package main

import (
	"fmt"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/cdp"
	"github.com/go-rod/rod/lib/launcher"
	"github.com/go-rod/rod/lib/utils"
)

func main() {
	cdp := cdp.New().
		// Here we can customize how to log the requests, responses, and events transferred between Rod and the browser.
		Logger(utils.Log(func(args ...interface{}) {
			switch v := args[0].(type) {
			case *cdp.Request:
				fmt.Printf("id: %d", v.ID)
			}
		})).
		Start(cdp.MustConnectWS(launcher.New().MustLaunch()))

	rod.New().Client(cdp).MustConnect().MustPage("http://mdn.dev")
}
Output:

Example (Page_pdf)
package main

import (
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/proto"
	"github.com/go-rod/rod/lib/utils"
	"github.com/ysmood/gson"
)

func main() {
	page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()

	// simple version
	page.MustPDF("my.pdf")

	// customized version
	pdf, _ := page.PDF(&proto.PagePrintToPDF{
		PaperWidth:  gson.Num(8.5),
		PaperHeight: gson.Num(11),
		PageRanges:  "1-3",
	})
	_ = utils.OutputFile("my.pdf", pdf)
}
Output:

Example (Page_screenshot)
package main

import (
	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/proto"
	"github.com/go-rod/rod/lib/utils"
	"github.com/ysmood/gson"
)

func main() {
	page := rod.New().MustConnect().MustPage("https://github.com").MustWaitLoad()

	// simple version
	page.MustScreenshot("my.png")

	// customization version
	img, _ := page.Screenshot(true, &proto.PageCaptureScreenshot{
		Format:  proto.PageCaptureScreenshotFormatJpeg,
		Quality: gson.Int(90),
		Clip: &proto.PageViewport{
			X:      0,
			Y:      0,
			Width:  300,
			Height: 200,
			Scale:  1,
		},
		FromSurface: true,
	})
	_ = utils.OutputFile("my.jpg", img)
}
Output:

Example (Race_selectors)

Show how to handle multiple results of an action. Such as when you login a page, the result can be success or wrong password.

package main

import (
	"fmt"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/input"
)

func main() {
	const username = ""
	const password = ""

	browser := rod.New().MustConnect()

	page := browser.MustPage("https://leetcode.com/accounts/login/")

	page.MustElement("#id_login").MustInput(username)
	page.MustElement("#id_password").MustInput(password).MustType(input.Enter)

	// It will keep retrying until one selector has found a match
	elm := page.Race().Element(".nav-user-icon-base").MustHandle(func(e *rod.Element) {
		// print the username after successful login
		fmt.Println(*e.MustAttribute("title"))
	}).Element("[data-cy=sign-in-error]").MustDo()

	if elm.MustMatches("[data-cy=sign-in-error]") {
		// when wrong username or password
		panic(elm.MustText())
	}
}
Output:

Example (States)

Shows how to update the state of the current page. In this example we enable the network domain.

package main

import (
	"fmt"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/proto"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	// LoadState detects whether the network domain is enabled or not.
	fmt.Println(page.LoadState(&proto.NetworkEnable{}))

	_ = proto.NetworkEnable{}.Call(page)

	// Check if the network domain is successfully enabled.
	fmt.Println(page.LoadState(&proto.NetworkEnable{}))

}
Output:

false
true
Example (Wait_for_animation)

Rod uses mouse cursor to simulate clicks, so if a button is moving because of animation, the click may not work as expected. We usually use WaitStable to make sure the target isn't changing anymore.

package main

import (
	"fmt"

	"github.com/go-rod/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://getbootstrap.com/docs/4.0/components/modal/")

	page.MustWaitLoad().MustElement("[data-target='#exampleModalLive']").MustClick()

	saveBtn := page.MustElementR("#exampleModalLive button", "Close")

	// Here, WaitStable will wait until the button's position and size become stable.
	saveBtn.MustWaitStable().MustClick().MustWaitInvisible()

	fmt.Println("done")

}
Output:

done
Example (Wait_for_request)

When you want to wait for an ajax request to complete, this example will be useful.

package main

import (
	"fmt"

	"github.com/go-rod/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://duckduckgo.com/")

	// Start to analyze request events
	wait := page.MustWaitRequestIdle()

	// This will trigger the search ajax request
	page.MustElement("#search_form_input_homepage").MustClick().MustInput("lisp")

	// Wait until there's no active requests
	wait()

	// We want to make sure that after waiting, there are some autocomplete
	// suggestions available.
	fmt.Println(len(page.MustElements(".search__autocomplete .acp")) > 0)

}
Output:

true

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultLogger = log.New(os.Stdout, "[rod] ", log.LstdFlags)

rod的默认Logger

View Source
var DefaultSleeper = func() utils.Sleeper {
	return utils.BackoffSleeper(100*time.Millisecond, time.Second, nil)
}

DefaultSleeper为重试生成默认的睡眠器,它使用backoff来增长间隔时间。 增长情况如下:

A(0) = 100ms, A(n) = A(n-1) * random[1.9, 2.1), A(n) < 1s

为什么默认值不是RequestAnimationFrame或DOM更改事件,是因为如果重试从未结束,它很容易淹没程序。但您可以随时轻松地将其配置为所需内容。

Functions

func NotFoundSleeper

func NotFoundSleeper() utils.Sleeper

NotFoundSleeper returns ErrElementNotFound on the first call

func Try

func Try(fn func()) (err error)

试着用recover来尝试fn,将panic作为rod.ErrTry返回。

Types

type Browser

type Browser struct {
	// BrowserContextID是隐身窗口的id。
	BrowserContextID proto.BrowserBrowserContextID
	// contains filtered or unexported fields
}

Browser 代表的是 browser. 它不依赖于文件系统,它可以与远程浏览器无缝工作。 要检查可用于从CLI快速启用选项的环境变量,请检查此处: https://pkg.go.dev/github.com/go-rod/rod/lib/defaults

func New

func New() *Browser

新创建一个浏览器控制器. 模拟设备的DefaultDevice被设置为devices.LaptopWithMDPIScreen.Landescape(),它可以使实际视图区域 小于浏览器窗口,你可以使用NoDefaultDevice来禁用它。

func (*Browser) Call

func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error)

Call 用于直接调用原始cdp接口

func (*Browser) CancelTimeout

func (b *Browser) CancelTimeout() *Browser

CancelTimeout 取消当前超时上下文,并返回具有父上下文的克隆

func (*Browser) Client

func (b *Browser) Client(c CDPClient) *Browser

Client 设置cdp的客户端

func (*Browser) Close

func (b *Browser) Close() error

Close 关闭浏览器

func (*Browser) Connect

func (b *Browser) Connect() error

Connect 用于连接浏览器并且控制浏览器. 如果连接失败,尝试启动一个本地浏览器,如果没有找到本地浏览器,尝试下载一个。

func (*Browser) Context

func (b *Browser) Context(ctx context.Context) *Browser

Context 返回具有指定ctx的克隆,用于链式子操作

func (*Browser) ControlURL

func (b *Browser) ControlURL(url string) *Browser

ControlURL设置远程控制浏览器的URL。

func (*Browser) DefaultDevice

func (b *Browser) DefaultDevice(d devices.Device) *Browser

DefaultDevice为将来要模拟的新页面设置默认设备。 默认值是devices.LaptopWithMDPIScreen。 将其设置为devices.Clear来禁用它。

func (*Browser) DisableDomain

func (b *Browser) DisableDomain(sessionID proto.TargetSessionID, req proto.Request) (restore func())

DisableDomain and returns a restore function to restore previous state DisableDomain 返回一个恢复函数来恢复之前的状态

func (*Browser) EachEvent

func (b *Browser) EachEvent(callbacks ...interface{}) (wait func())

EachEvent与Page.EachEvent类似,但可以捕获整个浏览器的事件。

func (*Browser) EnableDomain

func (b *Browser) EnableDomain(sessionID proto.TargetSessionID, req proto.Request) (restore func())

EnableDomain and returns a restore function to restore previous state EnableDomain 返回一个恢复函数来恢复之前的 State

func (*Browser) Event

func (b *Browser) Event() <-chan *Message

Event 浏览器事件

func (*Browser) GetContext

func (b *Browser) GetContext() context.Context

GetContext 获取当前的ctx实例

func (*Browser) GetCookies

func (b *Browser) GetCookies() ([]*proto.NetworkCookie, error)

GetCookies 从浏览器获取Cookie

func (*Browser) HandleAuth

func (b *Browser) HandleAuth(username, password string) func() error

HandleAuth for the next basic HTTP authentication. HandleAuth用于下一次基本HTTP认证。 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 与Page.HijackRequests相同,但可以拦截整个浏览器的请求。

func (*Browser) IgnoreCertErrors

func (b *Browser) IgnoreCertErrors(enable bool) error

IgnoreCertErrors 开关。如果启用,所有证书错误将被忽略。

func (*Browser) Incognito

func (b *Browser) Incognito() (*Browser, error)

Incognito 创建了一个无痕浏览器

func (*Browser) LoadState

func (b *Browser) LoadState(sessionID proto.TargetSessionID, method proto.Request) (has bool)

LoadState into the method, seesionID can be empty. 在方法的LoadState中,sessionID可以为空。

func (*Browser) Logger

func (b *Browser) Logger(l utils.Logger) *Browser

Logger覆盖了默认的日志功能,用于追踪

func (*Browser) Monitor

func (b *Browser) Monitor(url string) *Browser

要侦听的监视器地址(如果不为空)。Browser.ServeMonitor的快捷方式

func (*Browser) MustClose

func (b *Browser) MustClose()

MustClose is similar to Browser.Close MustClose 类似于 Browser.Close

func (*Browser) MustConnect

func (b *Browser) MustConnect() *Browser

MustConnect is similar to Browser.Connect MustConnect 类似于 Browser.Connect

func (*Browser) MustGetCookies

func (b *Browser) MustGetCookies() []*proto.NetworkCookie

MustGetCookies is similar to Browser.GetCookies MustGetCookies 类似于 Browser.GetCookies

func (*Browser) MustHandleAuth

func (b *Browser) MustHandleAuth(username, password string) (wait func())

MustHandleAuth is similar to Browser.HandleAuth MustHandleAuth 类似于 Browser.HandleAuth

func (*Browser) MustIgnoreCertErrors

func (b *Browser) MustIgnoreCertErrors(enable bool) *Browser

MustIgnoreCertErrors is similar to Browser.IgnoreCertErrors MustIgnoreCertErrors 类似于 Browser.IgnoreCertErrors

func (*Browser) MustIncognito

func (b *Browser) MustIncognito() *Browser

MustIncognito is similar to Browser.Incognito MustIncognito 类似于 Browser.Incognito

func (*Browser) MustPage

func (b *Browser) MustPage(url ...string) *Page

MustPage is similar to Browser.Page. MustPage 类似于 MustPage The url list will be joined by "/". 网址列表将以"/"连接。网址列表将以"/"连接。

func (*Browser) MustPageFromTargetID

func (b *Browser) MustPageFromTargetID(targetID proto.TargetTargetID) *Page

MustPageFromTargetID is similar to Browser.PageFromTargetID MustPageFromTargetID 类似于 Browser.PageFromTargetID

func (*Browser) MustPages

func (b *Browser) MustPages() Pages

MustPages is similar to Browser.Pages Mustpages 类似于 Browser.Pages

func (*Browser) MustSetCookies

func (b *Browser) MustSetCookies(cookies ...*proto.NetworkCookie) *Browser

MustSetCookies is similar to Browser.SetCookies. MustSetCookies 类似于 Browser.SetCookies. If the len(cookies) is 0 it will clear all the cookies. 如果Cookie的长度为0,则会清空所有Cookie

func (*Browser) MustVersion

func (b *Browser) MustVersion() *proto.BrowserGetVersionResult

MustVersion is similar to Browser.Version. MustVersion 类似于 Browser.Version。

func (*Browser) MustWaitDownload

func (b *Browser) MustWaitDownload() func() []byte

MustWaitDownload is similar to Browser.WaitDownload. MustWaitDownload 类似于 Browser.WaitDownload. It will read the file into bytes then remove the file. 它将把文件读入字节,然后删除文件。

func (*Browser) NoDefaultDevice

func (b *Browser) NoDefaultDevice() *Browser

NoDefaultDevice is the same as DefaultDevice(devices.Clear)

func (*Browser) Page

func (b *Browser) Page(opts proto.TargetCreateTarget) (p *Page, err error)

Page 创建一个新的浏览器标签。如果opts.URL为空,默认值将是 "about:blank"。

func (*Browser) PageFromSession

func (b *Browser) PageFromSession(sessionID proto.TargetSessionID) *Page

PageFromSession 用于底层调试

func (*Browser) PageFromTarget

func (b *Browser) PageFromTarget(targetID proto.TargetTargetID) (*Page, error)

PageFromTarget 获取或创建一个Page实例。

func (*Browser) Pages

func (b *Browser) Pages() (Pages, error)

Pages 检索所有可见页面

func (*Browser) RemoveState

func (b *Browser) RemoveState(key interface{})

RemoveState a state 删除一个 state

func (*Browser) ServeMonitor

func (b *Browser) ServeMonitor(host string) string

ServeMonitor starts the monitor server. 启动一个监控服务 The reason why not to use "chrome://inspect/#devices" is one target cannot be driven by multiple controllers. 不使用 "chrome://inspect/#devices "的原因是一个目标不能被多个控制器驱动。

func (*Browser) SetCookies

func (b *Browser) SetCookies(cookies []*proto.NetworkCookieParam) error

SetCookies 为浏览器设置Cookie,如果Cookie为nil则将所有Cookie清零

func (*Browser) Sleeper

func (b *Browser) Sleeper(sleeper func() utils.Sleeper) *Browser

Sleeper 为链式子操作返回具有指定Sleeper的克隆

func (*Browser) SlowMotion

func (b *Browser) SlowMotion(delay time.Duration) *Browser

SlowMotion设置每个控制动作的延迟,如模拟人的输入。

func (*Browser) Timeout

func (b *Browser) Timeout(d time.Duration) *Browser

Timeout 返回一个克隆,其中包含所有链接子操作的指定总超时

func (*Browser) Trace

func (b *Browser) Trace(enable bool) *Browser

Trace 启用/禁用 页面上输入动作的视觉追踪。

func (*Browser) Version

func (b *Browser) Version() (*proto.BrowserGetVersionResult, error)

Version 获取浏览器的版本信息

func (*Browser) WaitDownload

func (b *Browser) WaitDownload(dir string) func() (info *proto.PageDownloadWillBegin)

WaitDownload 返回一个helper,以获得下一个下载文件。 文件路径:

filepath.Join(dir, info.GUID)

func (*Browser) WaitEvent

func (b *Browser) WaitEvent(e proto.Event) (wait func())

WaitEvent 等待下一个事件的发生,时间为一次。它也会将数据加载到事件对象中。

func (*Browser) WithCancel

func (b *Browser) WithCancel() (*Browser, func())

WithCancel 返回带有上下文取消函数的克隆

func (*Browser) WithPanic

func (b *Browser) WithPanic(fail func(interface{})) *Browser

WithPanic returns a browser clone with the specified panic function. WithPanic返回具有指定panic函数的浏览器克隆。 The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit() or panic inside it. 失败时必须立即停止当前goroutine的执行,比如使用runtime.Goexit()或在其内部发生panic。

type BrowserPool

type BrowserPool chan *Browser

浏览器池(BrowserPool)以线程安全的方式限制同一时间内的浏览器数量。 使用通道来限制并发性是一种常见的做法,这对rod来说并不特别。 这个helper程序更像是一个使用Go Channel的例子。 参考: https://golang.org/doc/effective_go#channels

func NewBrowserPool

func NewBrowserPool(limit int) BrowserPool

NewBrowserPool 实例

func (BrowserPool) Cleanup

func (bp BrowserPool) Cleanup(iteratee func(*Browser))

清理 helper

func (BrowserPool) Get

func (bp BrowserPool) Get(create func() *Browser) *Browser

从池中获取一个浏览器。使用BrowserPool.Put来使它以后可以重复使用。

func (BrowserPool) Put

func (bp BrowserPool) Put(p *Browser)

将一个浏览器放回池中

type CDPClient

type CDPClient interface {
	Event() <-chan *cdp.Event
	Call(ctx context.Context, sessionID, method string, params interface{}) ([]byte, error)
}

CDPClient 通常被用来使rod不受副作用影响。例如,代理所有rod的IO。

type Element

type Element struct {
	Object *proto.RuntimeRemoteObject
	// contains filtered or unexported fields
}

Element 代表DOM中的元素

func (*Element) Attribute

func (el *Element) Attribute(name string) (*string, error)

Attribute DOM对象的属性 Attribute vs Property: https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html

func (*Element) BackgroundImage

func (el *Element) BackgroundImage() ([]byte, error)

BackgroundImage 返回元素的css背景图像

func (*Element) Blur

func (el *Element) Blur() error

Blur 类似于方法 Blur

func (*Element) Call

func (el *Element) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error)

Call 实现proto.Client

func (*Element) CancelTimeout

func (el *Element) CancelTimeout() *Element

CancelTimeout 取消当前超时上下文,并返回具有父上下文的克隆

func (*Element) CanvasToImage

func (el *Element) CanvasToImage(format string, quality float64) ([]byte, error)

CanvastoiImage 获取画布的图像数据。 默认格式为image/png。 默认质量为0.92。 doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

func (*Element) Click

func (el *Element) Click(button proto.InputMouseButton) error

Click 会像人一样按下然后释放按钮。 在执行操作之前,它将尝试滚动到元素,将鼠标悬停在该元素上,等待该元素可交互并启用。

func (*Element) ContainsElement

func (el *Element) ContainsElement(target *Element) (bool, error)

ContainesElement 检查目标是否是或在元素内。

func (*Element) Context

func (el *Element) Context(ctx context.Context) *Element

Context 返回具有指定ctx的克隆,用于链式子操作

func (*Element) Describe

func (el *Element) Describe(depth int, pierce bool) (*proto.DOMNode, error)

Describe 描述当前元素。深度是应检索子级的最大深度,默认为1,对整个子树使用-1,或提供大于0的整数。 pierce决定在返回子树时是否要遍历iframes和影子根。 返回的proto.DOMNode。NodeID将始终为空,因为NodeID不稳定(当proto.DOMDocumentUpdated被触发时, 页面上的所有NodeID都将被重新分配到另一个值)。我们不建议使用NodeID,而是使用BackendNodeID来标识元素。

func (*Element) Element

func (el *Element) Element(selector string) (*Element, error)

Element returns the first child that matches the css selector 返回第一个和CSS选择器匹配的子元素

func (*Element) ElementByJS

func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error)

ElementByJS returns the element from the return value of the js ElementByJS 从 js 的返回值中返回该元素。

func (*Element) ElementR

func (el *Element) ElementR(selector, jsRegex string) (*Element, error)

ElementR returns the first child element that matches the css selector and its text matches the jsRegex. ElementR返回符合css选择器的第一个子元素,并且其文本符合jsRegex。

func (*Element) ElementX

func (el *Element) ElementX(xPath string) (*Element, error)

ElementX returns the first child that matches the XPath selector 返回第一个和 XPath 选择器相匹配的子元素

func (*Element) Elements

func (el *Element) Elements(selector string) (Elements, error)

Elements returns all elements that match the css selector 返回和 CSS 选择器相匹配的所有元素

func (*Element) ElementsByJS

func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error)

ElementsByJS returns the elements from the return value of the js ElementsByJS 从 js 的返回值中返回元素。

func (*Element) ElementsX

func (el *Element) ElementsX(xpath string) (Elements, error)

ElementsX returns all elements that match the XPath selector 返回和 XPath 选择器相匹配的所有元素

func (*Element) Equal

func (el *Element) Equal(elm *Element) (bool, error)

Equal 检查两个元素是否相等。

func (*Element) Eval

func (el *Element) Eval(js string, params ...interface{}) (*proto.RuntimeRemoteObject, error)

Eval 是Element.Evaluate的一个快捷方式,其中AwaitPromise、ByValue和AutoExp设置为 "true"。

func (*Element) Evaluate

func (el *Element) Evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error)

Evaluate 只是Page.Evaluate的一个快捷方式,This设置为当前元素。

func (*Element) Focus

func (el *Element) Focus() error

Focus 设置指定元素的焦点 在执行之前,它将尝试滚动到该元素。

func (*Element) Frame

func (el *Element) Frame() (*Page, error)

Frame 创建一个表示iframe的页面实例

func (*Element) GetContext

func (el *Element) GetContext() context.Context

GetContext 获取当前ctx的实例

func (*Element) GetSessionID

func (el *Element) GetSessionID() proto.TargetSessionID

GetSessionID 接口

func (*Element) HTML

func (el *Element) HTML() (string, error)

HTML 元素的HTML

func (*Element) Has

func (el *Element) Has(selector string) (bool, *Element, error)

Has an element that matches the css selector 判断是否有和CSS选择器相匹配的元素

func (*Element) HasR

func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error)

HasR returns true if a child element that matches the css selector and its text matches the jsRegex. 如果有一个符合css选择器的子元素,并且其文本符合jsRegex,则HasR返回true。

func (*Element) HasX

func (el *Element) HasX(selector string) (bool, *Element, error)

HasX an element that matches the XPath selector 判断是否有和XPath相匹配的元素

func (*Element) Hover

func (el *Element) Hover() error

Hover 将鼠标停在元素的中心 在执行该操作之前,它将尝试滚动到该元素并等待其可交互。

func (*Element) Input

func (el *Element) Input(text string) error

Input 聚焦在该元素上并输入文本. 在执行操作之前,它将滚动到元素,等待其可见、启用和可写。 要清空输入,可以使用el.SelectAllText().MustInput(“”)之类的命令

func (*Element) InputTime

func (el *Element) InputTime(t time.Time) error

InputTime 聚焦该元素及其输入时间。 在执行操作之前,它将滚动到元素,等待其可见、启用和可写。 它将等待元素可见、启用和可写。

func (*Element) Interactable

func (el *Element) Interactable() (pt *proto.Point, err error)

Interactable 检查该元素是否可以与光标交互。 光标可以是鼠标、手指、手写笔等。 如果不是可交互的,Err将是ErrNotInteractable,例如当被一个模态框覆盖时。

func (*Element) KeyActions

func (el *Element) KeyActions() (*KeyActions, error)

KeyActions 与Page.KeyActions类似。 在执行操作之前,它将尝试滚动到该元素并将焦点集中在该元素上。

func (*Element) Matches

func (el *Element) Matches(selector string) (bool, error)

Matches 检查css选择器是否可以选择元素

func (*Element) MoveMouseOut

func (el *Element) MoveMouseOut() error

MoveMouseOut 将鼠标移出当前元素

func (*Element) MustAttribute

func (el *Element) MustAttribute(name string) *string

MustAttribute is similar to Element.Attribute MustAttribute 类似于 Element.Attribute

func (*Element) MustBackgroundImage

func (el *Element) MustBackgroundImage() []byte

MustBackgroundImage is similar to Element.BackgroundImage MustBackgroundImage 类似于 Element.BackgroundImage

func (*Element) MustBlur

func (el *Element) MustBlur() *Element

MustBlur is similar to Element.Blur MustBlur 类似于 Element.Blur

func (*Element) MustCanvasToImage

func (el *Element) MustCanvasToImage() []byte

MustCanvasToImage is similar to Element.CanvasToImage MustCanvasToImage 类似于 Element.CanvasToImage

func (*Element) MustClick

func (el *Element) MustClick() *Element

MustClick is similar to Element.Click MustClick 类似于 Element.Click

func (*Element) MustContainsElement

func (el *Element) MustContainsElement(target *Element) bool

MustContainsElement is similar to Element.ContainsElement MustContainsElement 类似于 Element.ContainsElement

func (*Element) MustDescribe

func (el *Element) MustDescribe() *proto.DOMNode

MustDescribe is similar to Element.Describe MustDescribe 类似于 Element.Describe

func (*Element) MustElement

func (el *Element) MustElement(selector string) *Element

MustElement is similar to Element.Element MustElement 类似于 Element.Element

func (*Element) MustElementByJS

func (el *Element) MustElementByJS(js string, params ...interface{}) *Element

MustElementByJS is similar to Element.ElementByJS MustElementByJS 类似于 Element.ElementByJS

func (*Element) MustElementR

func (el *Element) MustElementR(selector, regex string) *Element

MustElementR is similar to Element.ElementR MustElementR 类似于 Element.ElementR

func (*Element) MustElementX

func (el *Element) MustElementX(xpath string) *Element

MustElementX is similar to Element.ElementX MustElementX 类似于 Element.ElementX

func (*Element) MustElements

func (el *Element) MustElements(selector string) Elements

MustElements is similar to Element.Elements MustElements 类似于 Element.Elements

func (*Element) MustElementsByJS

func (el *Element) MustElementsByJS(js string, params ...interface{}) Elements

MustElementsByJS is similar to Element.ElementsByJS MustElementsByJS 类似于 Element.ElementsByJS

func (*Element) MustElementsX

func (el *Element) MustElementsX(xpath string) Elements

MustElementsX is similar to Element.ElementsX MustElementsX 类似于 Element.ElementsX

func (*Element) MustEqual

func (el *Element) MustEqual(elm *Element) bool

MustEqual is similar to Element.Equal MustEqual 类似于 Element.Equal

func (*Element) MustEval

func (el *Element) MustEval(js string, params ...interface{}) gson.JSON

MustEval is similar to Element.Eval MustEval 类似于 Element.Eval

func (*Element) MustFocus

func (el *Element) MustFocus() *Element

MustFocus is similar to Element.Focus MustFocus 类似于 Element.Focus

func (*Element) MustFrame

func (el *Element) MustFrame() *Page

MustFrame is similar to Element.Frame MustFrame 类似于 Element.Frame

func (*Element) MustHTML

func (el *Element) MustHTML() string

MustHTML is similar to Element.HTML MustHTML 类似于 Element.HTML

func (*Element) MustHas

func (el *Element) MustHas(selector string) bool

MustHas is similar to Element.Has MustHas 类似于 Element.Has

func (*Element) MustHasR

func (el *Element) MustHasR(selector, regex string) bool

MustHasR is similar to Element.HasR MustHasR 类似于 Element.HasR

func (*Element) MustHasX

func (el *Element) MustHasX(selector string) bool

MustHasX is similar to Element.HasX MustHasX 类似于 Element.HasX

func (*Element) MustHover

func (el *Element) MustHover() *Element

MustHover is similar to Element.Hover MustHover 类似于 Element.Hover

func (*Element) MustInput

func (el *Element) MustInput(text string) *Element

MustInput is similar to Element.Input MustInput 类似于 Element.Input

func (*Element) MustInputTime

func (el *Element) MustInputTime(t time.Time) *Element

MustInputTime is similar to Element.Input MustInputTime 类似于 Element.Input

func (*Element) MustInteractable

func (el *Element) MustInteractable() bool

MustInteractable is similar to Element.Interactable MustInteractable 类似于 Element.Interactable

func (*Element) MustKeyActions

func (el *Element) MustKeyActions() *KeyActions

MustKeyActions is similar to Element.KeyActions MustKeyActions 类似于 Element.KeyActions

func (*Element) MustMatches

func (el *Element) MustMatches(selector string) bool

MustMatches is similar to Element.Matches MustMatches 类似于 Element.Matches

func (*Element) MustMoveMouseOut

func (el *Element) MustMoveMouseOut() *Element

MustMoveMouseOut is similar to Element.MoveMouseOut MustMoveMouseOut 类似于 Element.MoveMouseOut

func (*Element) MustNext

func (el *Element) MustNext() *Element

MustNext is similar to Element.Next MustNext 类似于 Element.Next

func (*Element) MustParent

func (el *Element) MustParent() *Element

MustParent is similar to Element.Parent MustParent 类似于 Element.Parent

func (*Element) MustParents

func (el *Element) MustParents(selector string) Elements

MustParents is similar to Element.Parents MustParents 类似于 Element.Parents

func (*Element) MustPrevious

func (el *Element) MustPrevious() *Element

MustPrevious is similar to Element.Previous MustPrevious 类似于 Element.Previous

func (*Element) MustProperty

func (el *Element) MustProperty(name string) gson.JSON

MustProperty is similar to Element.Property MustProperty 类似于 Element.Property

func (*Element) MustRelease

func (el *Element) MustRelease()

MustRelease is similar to Element.Release MustRelease 类似于 Element.Release

func (*Element) MustRemove

func (el *Element) MustRemove()

MustRemove the element from the page MustRemove 从页面上移除相关元素

func (*Element) MustResource

func (el *Element) MustResource() []byte

MustResource is similar to Element.Resource MustResource 类似于 Element.Resource

func (*Element) MustScreenshot

func (el *Element) MustScreenshot(toFile ...string) []byte

MustScreenshot is similar to Element.Screenshot MustScreenshot 类似于 Element.Screenshot

func (*Element) MustScrollIntoView

func (el *Element) MustScrollIntoView() *Element

MustScrollIntoView is similar to Element.ScrollIntoView MustScrollIntoView 类似于 Element.ScrollIntoView

func (*Element) MustSelect

func (el *Element) MustSelect(selectors ...string) *Element

MustSelect is similar to Element.Select MustSelect 类似于 Element.Select

func (*Element) MustSelectAllText

func (el *Element) MustSelectAllText() *Element

MustSelectAllText is similar to Element.SelectAllText MustSelectAllText 类似于 Element.SelectAllText

func (*Element) MustSelectText

func (el *Element) MustSelectText(regex string) *Element

MustSelectText is similar to Element.SelectText MustSelectText 类似于 Element.SelectText

func (*Element) MustSetFiles

func (el *Element) MustSetFiles(paths ...string) *Element

MustSetFiles is similar to Element.SetFiles MustSetFiles 类似于 Element.SetFiles

func (*Element) MustShadowRoot

func (el *Element) MustShadowRoot() *Element

MustShadowRoot is similar to Element.ShadowRoot MustShadowRoot 类似于 Element.ShadowRoot

func (*Element) MustShape

func (el *Element) MustShape() *proto.DOMGetContentQuadsResult

MustShape is similar to Element.Shape MustShape 类似于 Element.Shape

func (*Element) MustTap

func (el *Element) MustTap() *Element

MustTap is similar to Element.Tap MustTap 类似于 Element.Tap

func (*Element) MustText

func (el *Element) MustText() string

MustText is similar to Element.Text MustText 类似于 Element.Text

func (*Element) MustType

func (el *Element) MustType(keys ...input.Key) *Element

MustType is similar to Element.Type MustType 类似于 Element.Type

func (*Element) MustVisible

func (el *Element) MustVisible() bool

MustVisible is similar to Element.Visible MustVisible 类似于 Element.Visible

func (*Element) MustWait

func (el *Element) MustWait(js string, params ...interface{}) *Element

MustWait is similar to Element.Wait MustWait 类似于 Element.Wait

func (*Element) MustWaitEnabled

func (el *Element) MustWaitEnabled() *Element

MustWaitEnabled is similar to Element.WaitEnabled MustWaitEnabled 类似于 Element.WaitEnabled

func (*Element) MustWaitInteractable

func (el *Element) MustWaitInteractable() *Element

MustWaitInteractable is similar to Element.WaitInteractable MustWaitInteractable 类似于 Element.WaitInteractable

func (*Element) MustWaitInvisible

func (el *Element) MustWaitInvisible() *Element

MustWaitInvisible is similar to Element.WaitInvisible MustWaitInvisible 类似于 Element.WaitInvisible

func (*Element) MustWaitLoad

func (el *Element) MustWaitLoad() *Element

MustWaitLoad is similar to Element.WaitLoad MustWaitLoad 类似于 Element.WaitLoad

func (*Element) MustWaitStable

func (el *Element) MustWaitStable() *Element

MustWaitStable is similar to Element.WaitStable MustWaitStable 类似于 Element.WaitStable

func (*Element) MustWaitVisible

func (el *Element) MustWaitVisible() *Element

MustWaitVisible is similar to Element.WaitVisible MustWaitVisible 类似于 Element.WaitVisible

func (*Element) MustWaitWritable

func (el *Element) MustWaitWritable() *Element

MustWaitWritable is similar to Element.WaitWritable MustWaitWritable 类似于 Element.WaitWritable

func (*Element) Next

func (el *Element) Next() (*Element, error)

Next returns the next sibling element in the DOM tree 返回DOM树中的下一个同级元素

func (*Element) Overlay

func (el *Element) Overlay(msg string) (removeOverlay func())

Overlay msg on the element 在元素上叠加 msg

func (*Element) Page

func (el *Element) Page() *Page

Page 元素所在的页面

func (*Element) Parent

func (el *Element) Parent() (*Element, error)

Parent returns the parent element in the DOM tree 返回 DOM 树中的父元素。

func (*Element) Parents

func (el *Element) Parents(selector string) (Elements, error)

Parents that match the selector 和选择器匹配的父元素。

func (*Element) Previous

func (el *Element) Previous() (*Element, error)

Previous returns the previous sibling element in the DOM tree 返回DOM树中的上一个同级元素

func (*Element) Property

func (el *Element) Property(name string) (gson.JSON, error)

Property DOM对象的属性 Property vs Attribute: https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html

func (*Element) Release

func (el *Element) Release() error

Release 是Page.Release(el.Object)的快捷方式

func (*Element) Remove

func (el *Element) Remove() error

Remove 从页面中删除元素

func (*Element) Resource

func (el *Element) Resource() ([]byte, error)

Resource 返回当前元素的“src”内容。例如<img src=“a.jpg”>的jpg

func (*Element) Screenshot

func (el *Element) Screenshot(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error)

Screenshot 元素区域的屏幕截图

func (*Element) ScrollIntoView

func (el *Element) ScrollIntoView() error

ScrollIntoView 将当前元素滚动到浏览器窗口的可见区域中(如果它尚未在可见区域内)。

func (*Element) Select

func (el *Element) Select(selectors []string, selected bool, t SelectorType) error

Select 选择与选择器匹配的子选项元素。 在操作之前,它将滚动到元素,等待它可见。 如果没有与选择器匹配的选项,它将返回ErrElementNotFound。

func (*Element) SelectAllText

func (el *Element) SelectAllText() error

SelectAllText 选择所有文本 在执行操作之前,它将尝试滚动到该元素并将焦点集中在该元素上。

func (*Element) SelectText

func (el *Element) SelectText(regex string) error

SelectText 选择与正则表达式匹配的文本。 在执行操作之前,它将尝试滚动到该元素并将焦点集中在该元素上。

func (*Element) SetFiles

func (el *Element) SetFiles(paths []string) error

SetFiles 设置当前文件输入元素的文件

func (*Element) ShadowRoot

func (el *Element) ShadowRoot() (*Element, error)

ShadowRoot ShadowRoot返回此元素的影子根

func (*Element) Shape

func (el *Element) Shape() (*proto.DOMGetContentQuadsResult, error)

Shape DOM元素内容的形状。该形状是一组4边多边形(4角)。 4-gon不一定是一个长方形。4-gon可以彼此分开。 例如,我们使用2个4角来描述以下形状:

  ____________          ____________
 /        ___/    =    /___________/    +     _________
/________/                                   /________/

func (*Element) Sleeper

func (el *Element) Sleeper(sleeper func() utils.Sleeper) *Element

Sleeper 为链式子操作返回具有指定Sleeper的克隆

func (*Element) String

func (el *Element) String() string

String 接口

func (*Element) Tap

func (el *Element) Tap() error

Tap 将滚动到按钮并像人类一样点击它。 在执行此操作之前,它将尝试滚动到元素,并等待其可交互并启用。

func (*Element) Text

func (el *Element) Text() (string, error)

Text 元素显示的文本

func (*Element) Timeout

func (el *Element) Timeout(d time.Duration) *Element

Timeout 返回一个克隆,其中包含所有链接子操作的指定总超时

func (*Element) Type

func (el *Element) Type(keys ...input.Key) error

Type 与Keyboard.Type类似。 在执行操作之前,它将尝试滚动到该元素并将焦点集中在该元素上。

func (*Element) Visible

func (el *Element) Visible() (bool, error)

Visible 如果元素在页面上可见,则返回true

func (*Element) Wait

func (el *Element) Wait(opts *EvalOptions) error

Wait 等待js返回true

func (*Element) WaitEnabled

func (el *Element) WaitEnabled() error

WaitEnabled 直到该元素未被禁用。 Doc for readonly: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly

func (*Element) WaitInteractable

func (el *Element) WaitInteractable() (pt *proto.Point, err error)

WaitInteractable 等待元素可交互。 它将在每次尝试时尝试滚动到元素。

func (*Element) WaitInvisible

func (el *Element) WaitInvisible() error

WaitInvisible 直到元件不可见

func (*Element) WaitLoad

func (el *Element) WaitLoad() error

WaitLoad 类似于<img>元素的等待加载

func (*Element) WaitStable

func (el *Element) WaitStable(d time.Duration) error

WaitStable 等待直到在d持续时间内没有形状或位置变化。 小心,d不是最大等待超时,它是最不稳定的时间。 如果要设置超时,可以使用“Element.timeout”函数。

func (*Element) WaitStableRAF

func (el *Element) WaitStableRAF() error

WaitStableRAF 等待直到连续两个动画帧的形状或位置没有变化。 如果要等待由JS而不是CSS触发的动画,最好使用Element.WaitStable。 关于 animation frame: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

func (*Element) WaitVisible

func (el *Element) WaitVisible() error

WaitVisible 直到元素可见

func (*Element) WaitWritable

func (el *Element) WaitWritable() error

WaitWritable 直到该元素不是只读的。 Doc for disabled: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled

func (*Element) WithCancel

func (el *Element) WithCancel() (*Element, func())

WithCancel 返回带有上下文取消函数的克隆

func (*Element) WithPanic

func (el *Element) WithPanic(fail func(interface{})) *Element

WithPanic returns an element clone with the specified panic function. WithPanic 返回一个带有指定 panic 函数的元素的克隆 The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit() or panic inside it.

type Elements

type Elements []*Element

Elements provides some helpers to deal with element list Elements 提供了一些帮助工具来处理元素列表

func (Elements) Empty

func (els Elements) Empty() bool

Empty returns true if the list is empty 判断 Elements 是否为空

func (Elements) First

func (els Elements) First() *Element

First returns the first element, if the list is empty returns nil First 返回第一个元素,如果元素列表是空的,则返回nil

func (Elements) Last

func (els Elements) Last() *Element

Last returns the last element, if the list is empty returns nil Last 返回最后一个元素,如果元素列表是空的,则返回nil

type ErrCovered

type ErrCovered struct {
	*Element
}

ErrCovered error.

func (*ErrCovered) Error

func (e *ErrCovered) Error() string

Error ...

func (*ErrCovered) Is

func (e *ErrCovered) Is(err error) bool

Is interface

func (*ErrCovered) Unwrap

func (e *ErrCovered) Unwrap() error

Unwrap ...

type ErrElementNotFound

type ErrElementNotFound struct {
}

ErrElementNotFound error

func (*ErrElementNotFound) Error

func (e *ErrElementNotFound) Error() string

type ErrEval

type ErrEval struct {
	*proto.RuntimeExceptionDetails
}

ErrEval error

func (*ErrEval) Error

func (e *ErrEval) Error() string

func (*ErrEval) Is

func (e *ErrEval) Is(err error) bool

Is interface

type ErrExpectElement

type ErrExpectElement struct {
	*proto.RuntimeRemoteObject
}

ErrExpectElement error

func (*ErrExpectElement) Error

func (e *ErrExpectElement) Error() string

func (*ErrExpectElement) Is

func (e *ErrExpectElement) Is(err error) bool

Is interface

type ErrExpectElements

type ErrExpectElements struct {
	*proto.RuntimeRemoteObject
}

ErrExpectElements error

func (*ErrExpectElements) Error

func (e *ErrExpectElements) Error() string

func (*ErrExpectElements) Is

func (e *ErrExpectElements) Is(err error) bool

Is interface

type ErrInvisibleShape

type ErrInvisibleShape struct {
	*Element
}

ErrInvisibleShape error.

func (*ErrInvisibleShape) Error

func (e *ErrInvisibleShape) Error() string

Error ...

func (*ErrInvisibleShape) Is

func (e *ErrInvisibleShape) Is(err error) bool

Is interface

func (*ErrInvisibleShape) Unwrap

func (e *ErrInvisibleShape) Unwrap() error

Unwrap ...

type ErrNavigation

type ErrNavigation struct {
	Reason string
}

ErrNavigation error

func (*ErrNavigation) Error

func (e *ErrNavigation) Error() string

func (*ErrNavigation) Is

func (e *ErrNavigation) Is(err error) bool

Is interface

type ErrNoPointerEvents

type ErrNoPointerEvents struct {
	*Element
}

ErrNoPointerEvents error.

func (*ErrNoPointerEvents) Error

func (e *ErrNoPointerEvents) Error() string

Error ...

func (*ErrNoPointerEvents) Is

func (e *ErrNoPointerEvents) Is(err error) bool

Is interface

func (*ErrNoPointerEvents) Unwrap

func (e *ErrNoPointerEvents) Unwrap() error

Unwrap ...

type ErrNotInteractable

type ErrNotInteractable struct{}

ErrNotInteractable error. Check the doc of Element.Interactable for details.

func (*ErrNotInteractable) Error

func (e *ErrNotInteractable) Error() string

type ErrObjectNotFound

type ErrObjectNotFound struct {
	*proto.RuntimeRemoteObject
}

ErrObjectNotFound error

func (*ErrObjectNotFound) Error

func (e *ErrObjectNotFound) Error() string

func (*ErrObjectNotFound) Is

func (e *ErrObjectNotFound) Is(err error) bool

Is interface

type ErrPageCloseCanceled

type ErrPageCloseCanceled struct {
}

ErrPageCloseCanceled error

func (*ErrPageCloseCanceled) Error

func (e *ErrPageCloseCanceled) Error() string

type ErrPageNotFound

type ErrPageNotFound struct {
}

ErrPageNotFound error

func (*ErrPageNotFound) Error

func (e *ErrPageNotFound) Error() string

type ErrTry

type ErrTry struct {
	Value interface{}
	Stack string
}

ErrTry error

func (*ErrTry) Error

func (e *ErrTry) Error() string

func (*ErrTry) Is

func (e *ErrTry) Is(err error) bool

Is interface

func (*ErrTry) Unwrap

func (e *ErrTry) Unwrap() error

Unwrap stdlib interface

type EvalOptions

type EvalOptions struct {
	// If enabled the eval result will be a plain JSON value.
	// 如果启用,eval的结果会是普通JSON值
	// If disabled the eval result will be a reference of a remote js object.
	// 如果禁用,eval的结果会是一个JS对象的引用。
	ByValue bool

	AwaitPromise bool

	// ThisObj represents the "this" object in the JS
	// ThisObj 代表 JS 里面的 this
	ThisObj *proto.RuntimeRemoteObject

	// JS function definition to execute.
	// 要注入的 JS 函数
	JS string

	// JSArgs represents the arguments that will be passed to JS.
	// JSArgs 表示将被传递给 JS 函数的参数。
	// If an argument is *proto.RuntimeRemoteObject type, the corresponding remote object will be used.
	// 如果参数是 *proto.RuntimeRemoteObject 类型,将使用相应的远程对象。
	// Or it will be passed as a plain JSON value.
	// 或者它将作为普通JSON值传递。
	// When an arg in the args is a *js.Function, the arg will be cached on the page's js context.
	// 当args中的参数是*js.Function时,该参数将被缓存在页面的 js ctx中。
	// When the arg.Name exists in the page's cache, it reuse the cache without sending the definition to the browser again.
	// 当arg.Name存在于页面的缓存中时,它就会重新使用缓存,而不会再次将定义发送到浏览器。
	// Useful when you need to eval a huge js expression many times.
	// 当注入的 JS 体积非常大且要注入许多次时,是非常有效的。
	JSArgs []interface{}

	// Whether execution should be treated as initiated by user in the UI.
	// 在用户界面中是否应执行应由用户发起。
	UserGesture bool
}

EvalOptions for Page.Evaluate Page.Evaluate 配置项

func Eval

func Eval(js string, args ...interface{}) *EvalOptions

Eval creates a EvalOptions with ByValue set to true. 创建一个 ByValue 设置为 true 的 EvalOptions

func (*EvalOptions) ByObject

func (e *EvalOptions) ByObject() *EvalOptions

ByObject disables ByValue. 禁用 ByValue

func (*EvalOptions) ByPromise

func (e *EvalOptions) ByPromise() *EvalOptions

ByPromise enables AwaitPromise. 启用 AwaitPromise

func (*EvalOptions) ByUser

func (e *EvalOptions) ByUser() *EvalOptions

ByUser enables UserGesture. 启用 UserGesture.

func (*EvalOptions) String

func (e *EvalOptions) String() string

String interface

func (*EvalOptions) This

This set the obj as ThisObj 设置 This 的值

type Hijack

type Hijack struct {
	Request  *HijackRequest
	Response *HijackResponse
	OnError  func(error)

	// 跳过下一个 handler
	Skip bool

	// CustomState用于存储此context的内容
	CustomState interface{}
	// contains filtered or unexported fields
}

Hijack context

func (*Hijack) ContinueRequest

func (h *Hijack) ContinueRequest(cq *proto.FetchContinueRequest)

ContinueRequest 不被劫持。RequestID将由router设置,你不需要设置它。

func (*Hijack) LoadResponse

func (h *Hijack) LoadResponse(client *http.Client, loadBody bool) error

LoadResponse will send request to the real destination and load the response as default response to override. LoadResponse 将向实际目标发送请求,并将响应作为默认响应加载以覆盖。

func (*Hijack) MustLoadResponse

func (h *Hijack) MustLoadResponse()

MustLoadResponse is similar to Hijack.LoadResponse MustLoadResponse 类似于 Hijack.LoadResponse

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. 请求体,devtools API还不支持二进制数据,只能捕获字符串。

func (*HijackRequest) Header

func (ctx *HijackRequest) Header(key string) string

Header via a key 通过key获得相应的请求头的值

func (*HijackRequest) Headers

func (ctx *HijackRequest) Headers() proto.NetworkHeaders

Headers of request 请求的请求头

func (*HijackRequest) IsNavigation

func (ctx *HijackRequest) IsNavigation() bool

IsNavigation determines whether the request is a navigation request IsNavigation 确定请求是否是一个导航请求

func (*HijackRequest) JSONBody

func (ctx *HijackRequest) JSONBody() gson.JSON

JSONBody of the request 请求的JSONBody

func (*HijackRequest) Method

func (ctx *HijackRequest) Method() string

Method of the request 请求的方法

func (*HijackRequest) Req

func (ctx *HijackRequest) Req() *http.Request

Req returns the underlaying http.Request instance that will be used to send the request. Req返回将用于发送请求的http.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. 设置请求的正文,如果obj是[]字节或字符串,将使用原始正文,否则将被编码为json。

func (*HijackRequest) SetContext

func (ctx *HijackRequest) SetContext(c context.Context) *HijackRequest

SetContext of the underlaying http.Request instance 设置底层http.Request实例的上下文。

func (*HijackRequest) Type

Type of the resource 资源的类型

func (*HijackRequest) URL

func (ctx *HijackRequest) URL() *url.URL

URL of the request 请求的URL

type HijackResponse

type HijackResponse struct {
	// contains filtered or unexported fields
}

HijackResponse context

func (*HijackResponse) Body

func (ctx *HijackResponse) Body() string

Body of the payload playload 的主体

func (*HijackResponse) Fail

Fail request

func (*HijackResponse) Headers

func (ctx *HijackResponse) Headers() http.Header

Headers returns the clone of response headers. 返回响应头的克隆 If you want to modify the response headers use HijackResponse.SetHeader . 如果想修改响应头请使用:HijackResponse.SetHeader

func (*HijackResponse) Payload

func (ctx *HijackResponse) Payload() *proto.FetchFulfillRequest

Payload to respond the request from the browser. 来自浏览器请求响应的 payload

func (*HijackResponse) SetBody

func (ctx *HijackResponse) SetBody(obj interface{}) *HijackResponse

SetBody of the payload, if obj is []byte or string, raw body will be used, else it will be encoded as json. 设置有效载荷的主体,如果obj是[]字节或字符串,将使用原始主体,否则将被编码为json。

func (*HijackResponse) SetHeader

func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse

SetHeader of the payload via key-value pairs 通过键值对儿为 playload 设置响应头

type HijackRouter

type HijackRouter struct {
	// contains filtered or unexported fields
}

HijackRouter 的context

func (*HijackRouter) Add

func (r *HijackRouter) Add(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error

为路由添加一个 hijack handler,模式的文档与“proto.FetchRequestPattern.URLPattern”相同。 即使在调用“Run”之后,也可以添加新的handler.

func (*HijackRouter) MustAdd

func (r *HijackRouter) MustAdd(pattern string, handler func(*Hijack)) *HijackRouter

MustAdd is similar to HijackRouter.Add MustAdd 类似于 HijackRouter.Add

func (*HijackRouter) MustRemove

func (r *HijackRouter) MustRemove(pattern string) *HijackRouter

MustRemove is similar to HijackRouter.Remove MustRemove 类似于 HijackRouter.Remove

func (*HijackRouter) MustStop

func (r *HijackRouter) MustStop()

MustStop is similar to HijackRouter.Stop MustStop 类似于 HijackRouter.Stop

func (*HijackRouter) Remove

func (r *HijackRouter) Remove(pattern string) error

Remove 通过 pattern 删除 handler

func (*HijackRouter) Run

func (r *HijackRouter) Run()

Run the router, after you call it, you shouldn't add new handler to it. Run 运行 router 在你调用它之后,就再不能给它添加新的 handler。

func (*HijackRouter) Stop

func (r *HijackRouter) Stop() error

Stop 停止router

type KeyAction

type KeyAction struct {
	Type KeyActionType
	Key  input.Key
}

KeyAction to perform 执行按键操作

type KeyActionType

type KeyActionType int

KeyActionType enum 枚举 KeyActionType

const (
	KeyActionPress KeyActionType = iota
	KeyActionRelease
	KeyActionTypeKey
)

KeyActionTypes

type KeyActions

type KeyActions struct {
	Actions []KeyAction
	// contains filtered or unexported fields
}

KeyActions to simulate 模拟按键操作

func (*KeyActions) Do

func (ka *KeyActions) Do() (err error)

Do the actions 执行相应的按键操作

func (*KeyActions) MustDo

func (ka *KeyActions) MustDo()

MustDo is similar to KeyActions.Do MustDo 类似于 KeyActions.Do

func (*KeyActions) Press

func (ka *KeyActions) Press(keys ...input.Key) *KeyActions

Press keys is guaranteed to have a release at the end of actions 用来确保每次操作结束后释放,再按下

func (*KeyActions) Release

func (ka *KeyActions) Release(keys ...input.Key) *KeyActions

Release keys 释放按键

func (*KeyActions) Type

func (ka *KeyActions) Type(keys ...input.Key) *KeyActions

Type will release the key immediately after the pressing Type 会立即释放按键

type Keyboard

type Keyboard struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Keyboard represents the keyboard on a page, it's always related the main frame keyboard 代表一个页面上的键盘,它总是与主frame相关

func (*Keyboard) MustType

func (k *Keyboard) MustType(key ...input.Key) *Keyboard

MustType is similar to Keyboard.Type MustType 类似于 Keyboard.Type

func (*Keyboard) Press

func (k *Keyboard) Press(key input.Key) error

Press the key down. To input characters that are not on the keyboard, such as Chinese or Japanese, you should use method like Page.InsertText . 按下按键 要输入键盘上没有的字符,如中文或日文,你应该使用类似Page.InsertText的方法。

func (*Keyboard) Release

func (k *Keyboard) Release(key input.Key) error

Release the key 释放按键

func (*Keyboard) Type

func (k *Keyboard) Type(keys ...input.Key) (err error)

Type releases the key after the press 按下后紧接着释放

type Message

type Message struct {
	SessionID proto.TargetSessionID
	Method    string
	// contains filtered or unexported fields
}

Message 代表一个cdp.Event

func (*Message) Load

func (msg *Message) Load(e proto.Event) bool

将数据加载到 e 中,如果 e 符合事件类型,则返回 true。

type Mouse

type Mouse struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Mouse represents the mouse on a page, it's always related the main frame 代表一个在页面中的鼠标,总是依赖于主frame

func (*Mouse) Click

func (m *Mouse) Click(button proto.InputMouseButton) error

Click the button. It's the combination of Mouse.Down and Mouse.Up 点击按钮。它是Mouse.Down和Mouse.Up的组合。

func (*Mouse) Down

func (m *Mouse) Down(button proto.InputMouseButton, clicks int) error

Down holds the button down 向下按住按钮

func (*Mouse) Move

func (m *Mouse) Move(x, y float64, steps int) error

Move to the absolute position with specified steps 以指定的步骤移动到绝对位置

func (*Mouse) MustClick

func (m *Mouse) MustClick(button proto.InputMouseButton) *Mouse

MustClick is similar to Mouse.Click MustClick 类似于 Mouse.Click

func (*Mouse) MustDown

func (m *Mouse) MustDown(button proto.InputMouseButton) *Mouse

MustDown is similar to Mouse.Down MustDown 类似于 Mouse.Down

func (*Mouse) MustMove

func (m *Mouse) MustMove(x, y float64) *Mouse

MustMove is similar to Mouse.Move MustMove 类似于 Mouse.Move

func (*Mouse) MustScroll

func (m *Mouse) MustScroll(x, y float64) *Mouse

MustScroll is similar to Mouse.Scroll MustScroll 类似于 Mouse.Scroll

func (*Mouse) MustUp

func (m *Mouse) MustUp(button proto.InputMouseButton) *Mouse

MustUp is similar to Mouse.Up MustUp 类似于 Mouse.Up

func (*Mouse) Scroll

func (m *Mouse) Scroll(offsetX, offsetY float64, steps int) error

Scroll the relative offset with specified steps 以指定的步骤滚动相对偏移量

func (*Mouse) Up

func (m *Mouse) Up(button proto.InputMouseButton, clicks int) error

Up releases the button 向上释放按钮

type Page

type Page struct {
	// TargetID is a unique ID for a remote page.
	// TargetID 每个页面独有的ID
	// It's usually used in events sent from the browser to tell which page an event belongs to.
	// 它通常用于从浏览器发送的事件中,以说明事件属于哪个页面。
	TargetID proto.TargetTargetID

	// FrameID is a unique ID for a browsing context.
	// FrameID 是浏览器 ctx 的独有ID
	// Usually, different FrameID means different javascript execution context.
	// 通常,不同的FrameID 意味着不同的JS执行ctx
	// Such as an iframe and the page it belongs to will have the same TargetID but different FrameIDs.
	// 如一个iframe和它所属的页面有相同的TargetID,但不同的FrameID。
	FrameID proto.PageFrameID

	// SessionID is a unique ID for a page attachment to a controller.
	// SessionID 是指向控制器的页面附件的唯一ID。
	// It's usually used in transport layer to tell which page to send the control signal.
	// 它通常用于传输层,告诉哪个页面要发送控制信号。
	// A page can attached to multiple controllers, the browser uses it distinguish controllers.
	// 一个页面可以附加到多个控制器,浏览器使用它来区分控制器。
	SessionID proto.TargetSessionID

	// devices // 页面中的设备
	Mouse    *Mouse
	Keyboard *Keyboard
	Touch    *Touch
	// contains filtered or unexported fields
}

Page represents the webpage. Page 代表网页页面 We try to hold as less states as possible. 我们会尽可能减少页面所拥有的状态 When a page is closed by Rod or not all the ongoing operations an events on it will abort. 当一个页面被Rod关闭或不是所有正在进行的操作时,它上的事件将中止。

Example (Pool)

We can use PagePool to concurrently control and reuse pages.

package main

import (
	"fmt"
	"sync"

	"github.com/go-rod/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	// We create a pool that will hold at most 3 pages which means the max concurrency is 3
	pool := rod.NewPagePool(3)

	// Create a page if needed
	create := func() *rod.Page {
		// We use MustIncognito to isolate pages with each other
		return browser.MustIncognito().MustPage()
	}

	yourJob := func() {
		page := pool.Get(create)
		defer pool.Put(page)

		page.MustNavigate("http://mdn.dev").MustWaitLoad()
		fmt.Println(page.MustInfo().Title)
	}

	// Run jobs concurrently
	wg := sync.WaitGroup{}
	for range "...." {
		wg.Add(1)
		go func() {
			defer wg.Done()
			yourJob()
		}()
	}
	wg.Wait()

	// cleanup pool
	pool.Cleanup(func(p *rod.Page) { p.MustClose() })

}
Output:

mdn.dev
mdn.dev
mdn.dev
mdn.dev

func (*Page) Activate

func (p *Page) Activate() (*Page, error)

Activate (focuses) the page 激活页面

func (*Page) AddScriptTag

func (p *Page) AddScriptTag(url, content string) error

AddScriptTag to page. If url is empty, content will be used. 向页面添加 Script 标签。如果url是空的,content参数将会被使用

func (*Page) AddStyleTag

func (p *Page) AddStyleTag(url, content string) error

AddStyleTag to page. If url is empty, content will be used. 向页面添加 CSS 标签。如果url是空的,content参数将会被使用

func (*Page) Browser

func (p *Page) Browser() *Browser

Browser of the page 页面所属的浏览器对象

func (*Page) Call

func (p *Page) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error)

Call implements the proto.Client 实现了 `proto.Client`

func (*Page) CancelTimeout

func (p *Page) CancelTimeout() *Page

CancelTimeout 取消当前超时上下文,并返回具有父上下文的克隆

func (*Page) Close

func (p *Page) Close() error

Close tries to close page, running its beforeunload hooks, if has any. 尝试关闭页面,如果有的话,它会运行 beforeunload 钩子函数。

func (*Page) Context

func (p *Page) Context(ctx context.Context) *Page

Context 返回具有指定ctx的克隆,用于链式子操作

func (*Page) Cookies

func (p *Page) Cookies(urls []string) ([]*proto.NetworkCookie, error)

Cookies returns the page cookies. By default it will return the cookies for current page. 用于返回当前页面的Cookies。默认返回当前页面的Cookies。 The urls is the list of URLs for which applicable cookies will be fetched. urls 是获取Cookies的URL列表

func (*Page) DisableDomain

func (p *Page) DisableDomain(method proto.Request) (restore func())

DisableDomain and returns a restore function to restore previous state DisableDomain 返回一个恢复函数来恢复之前的状态。

func (*Page) EachEvent

func (p *Page) EachEvent(callbacks ...interface{}) (wait func())

EachEvent of the specified event types, if any callback returns true the wait function will resolve, 指定事件类型的事件,如果任何回调返回 true 等待函数将会解决, The type of each callback is (? means optional): 每一个回调类型

func(proto.Event, proto.TargetSessionID?) bool?

You can listen to multiple event types at the same time like: 你可以监听很多事件类型同时:

browser.EachEvent(func(a *proto.A) {}, func(b *proto.B) {})

Such as subscribe the events to know when the navigation is complete or when the page is rendered. 例如订阅事件,以便于了解navigation何时完成或者页面何时渲染完成。 Here's an example to dismiss all dialogs/alerts on the page: 这里是一个关闭所有对话框的例子:

go page.EachEvent(func(e *proto.PageJavascriptDialogOpening) {
    _ = proto.PageHandleJavaScriptDialog{ Accept: false, PromptText: ""}.Call(page)
})()

func (*Page) Element

func (p *Page) Element(selector string) (*Element, error)

Element retries until an element in the page that matches the CSS selector, then returns the matched element. Element 会重试,直到页面中的元素与CSS选择器匹配,然后返回匹配的元素。

func (*Page) ElementByJS

func (p *Page) ElementByJS(opts *EvalOptions) (*Element, error)

ElementByJS returns the element from the return value of the js function. ElementByJS 从js函数的返回值返回元素。 If sleeper is nil, no retry will be performed. 如果 sleeper 是 nil,则不会执行重试 By default, it will retry until the js function doesn't return null. 默认情况下,会一直重试直到 JS 函数不会返回 null To customize the retry logic, check the examples of Page.Sleeper. 要自定义重试逻辑,请查看 Page.Sleeper 的示例。

func (*Page) ElementFromNode

func (p *Page) ElementFromNode(node *proto.DOMNode) (*Element, error)

ElementFromNode creates an Element from the node, NodeID or BackendNodeID must be specified. ElementFromNode从节点创建一个元素,必须指定NodeID或BackendNodeID。

func (*Page) ElementFromObject

func (p *Page) ElementFromObject(obj *proto.RuntimeRemoteObject) (*Element, error)

ElementFromObject creates an Element from the remote object id. ElementFromObject从远程对象id创建一个元素。

func (*Page) ElementFromPoint

func (p *Page) ElementFromPoint(x, y int) (*Element, error)

ElementFromPoint creates an Element from the absolute point on the page. ElementFromPoint从页面上的绝对点创建一个元素。 The point should include the window scroll offset. 该点应包括窗口滚动偏移量。

func (*Page) ElementR

func (p *Page) ElementR(selector, jsRegex string) (*Element, error)

ElementR retries until an element in the page that matches the css selector and it's text matches the jsRegex, then returns the matched element. ElementR 会重试,直到页面中出现符合css选择器的元素,并且其文本符合jsRegex,然后返回匹配的元素。

func (*Page) ElementX

func (p *Page) ElementX(xPath string) (*Element, error)

ElementX retries until an element in the page that matches one of the XPath selectors, then returns the matched element. ElementX 会重试,直到页面中的元素与XPath选择器匹配,然后返回匹配的元素。

func (*Page) Elements

func (p *Page) Elements(selector string) (Elements, error)

Elements returns all elements that match the css selector 返回和 CSS 选择器匹配的所有元素

func (*Page) ElementsByJS

func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error)

ElementsByJS returns the elements from the return value of the js ElementsByJS 从 js 的返回值中返回元素。

func (*Page) ElementsX

func (p *Page) ElementsX(xpath string) (Elements, error)

ElementsX returns all elements that match the XPath selector 返回和 XPath 选择器匹配的所有元素

func (*Page) Emulate

func (p *Page) Emulate(device devices.Device) error

Emulate the device, such as iPhone9. If device is devices.Clear, it will clear the override. 模拟设备,例如 IPhone9,。如果 devices是devcs.Clear,将会清除覆盖

func (*Page) EnableDomain

func (p *Page) EnableDomain(method proto.Request) (restore func())

EnableDomain and returns a restore function to restore previous state EnableDomain 返回一个恢复函数来恢复之前的 State

func (*Page) Eval

func (p *Page) Eval(js string, args ...interface{}) (*proto.RuntimeRemoteObject, error)

Eval is a shortcut for Page.Evaluate with AwaitPromise, ByValue set to true. Eval 是 当 AwaitPromise ByValue 为 True 时的 Page.Evaluate 的快捷 API

func (*Page) EvalOnNewDocument

func (p *Page) EvalOnNewDocument(js string) (remove func() error, err error)

EvalOnNewDocument Evaluates given script in every frame upon creation (before loading frame's scripts). 会在每一个新的 frame 创建时,执行给定的JS脚本

func (*Page) Evaluate

func (p *Page) Evaluate(opts *EvalOptions) (res *proto.RuntimeRemoteObject, err error)

Evaluate js on the page. 在页面中执行 JS

func (*Page) Event

func (p *Page) Event() <-chan *Message

Event of the page 页面上的事件

func (*Page) Expose

func (p *Page) Expose(name string, fn func(gson.JSON) (interface{}, error)) (stop func() error, err error)

Expose fn to the page's window object with the name. The exposure survives reloads. 将fn暴露给名为的页面窗口对象。exposure 在重新加载后仍然有效。 Call stop to unbind the fn. 调用 stop 可以解除 fn 的绑定

func (*Page) ExposeHelpers

func (p *Page) ExposeHelpers(list ...*js.Function)

ExposeHelpers helper functions to page's js context so that we can use the Devtools' console to debug them. 将ExposeHelpers的辅助函数放到页面的js ctx 中,这样我们就可以使用Devtools的控制台来调试它们。

func (*Page) GetContext

func (p *Page) GetContext() context.Context

GetContext 获取当前ctx实例

func (*Page) GetResource

func (p *Page) GetResource(url string) ([]byte, error)

GetResource content by the url. Such as image, css, html, etc. 通过URL获取页面中的资源,例如 image,css,html等 Use the proto.PageGetResourceTree to list all the resources. 使用 proto.PageGetResourceTree 会返回所有的资源

func (*Page) GetSessionID

func (p *Page) GetSessionID() proto.TargetSessionID

GetSessionID interface 获取 SessionID 的接口

func (*Page) GetWindow

func (p *Page) GetWindow() (*proto.BrowserBounds, error)

GetWindow position and size info 获取页面窗口大小信息

func (*Page) HTML

func (p *Page) HTML() (string, error)

HTML of the page 获取页面的HTML代码

func (*Page) HandleDialog

func (p *Page) HandleDialog() (
	wait func() *proto.PageJavascriptDialogOpening,
	handle func(*proto.PageHandleJavaScriptDialog) error,
)

HandleDialog accepts or dismisses next JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload). HandleDialog 接受或驳回下一个JavaScript发起的对话框(警报、确认、提示或onbeforeunload)。 Because modal dialog will block js, usually you have to trigger the dialog in another goroutine. 由于模态对话框将阻塞js,通常您必须在另一个goroutine中触发对话框。 For example:

wait, handle := page.MustHandleDialog()
go page.MustElement("button").MustClick()
wait()
handle(true, "")

func (*Page) Has

func (p *Page) Has(selector string) (bool, *Element, error)

Has an element that matches the css selector 在页面中用css selector查找某个元素是否存在

func (*Page) HasR

func (p *Page) HasR(selector, jsRegex string) (bool, *Element, error)

HasR an element that matches the css selector and its display text matches the jsRegex. 在页面中用css选择器匹配,其显示文本与jsRegex匹配,使用组合的方式查找某个元素是否存在。

func (*Page) HasX

func (p *Page) HasX(selector string) (bool, *Element, error)

HasX an element that matches the XPath selector 在页面中用XPath查找某个元素是否存在

func (*Page) HijackRequests

func (p *Page) HijackRequests() *HijackRouter

HijackRequests 创建一个新的路由器实例,用于劫持请求。 当使用路由器以外的Fetch domain时,应该停止。启用劫持功能会禁用页面缓存。但诸如304 Not Modified等仍将按预期工作。 劫持一个请求的整个过程:

browser --req-> rod ---> server ---> rod --res-> browser

The --req-> and --res-> 是可以修改的部分.

func (*Page) Info

func (p *Page) Info() (*proto.TargetTargetInfo, error)

Info of the page, such as the URL or title of the page 打印页面的信息,例页面的URL,标题等。

func (*Page) InsertText

func (p *Page) InsertText(text string) error

InsertText is like pasting text into the page 类似于将文本粘贴到页面中

func (*Page) IsIframe

func (p *Page) IsIframe() bool

IsIframe tells if it's iframe IsIframe 用于判断页面是否是一个iframe

func (*Page) KeyActions

func (p *Page) KeyActions() *KeyActions

KeyActions simulates the type actions on a physical keyboard. Useful when input shortcuts like ctrl+enter . KeyActions 模拟物理键盘上的类型操作。 尤其在执行像 ctrl+enter 快捷键时非常有用

func (*Page) LoadState

func (p *Page) LoadState(method proto.Request) (has bool)

LoadState into the method. 在方法中的LoadState

func (*Page) MustActivate

func (p *Page) MustActivate() *Page

MustActivate is similar to Page.Activate MustActivate 类似于 Page.Activate

func (*Page) MustAddScriptTag

func (p *Page) MustAddScriptTag(url string) *Page

MustAddScriptTag 类似于 Page.AddScriptTag

func (*Page) MustAddStyleTag

func (p *Page) MustAddStyleTag(url string) *Page

MustAddStyleTag is similar to Page.AddStyleTag MustAddStyleTag 类似于 Page.AddStyleTag

func (*Page) MustClose

func (p *Page) MustClose()

MustClose is similar to Page.Close MustClose 类似于 Page.Close

func (*Page) MustCookies

func (p *Page) MustCookies(urls ...string) []*proto.NetworkCookie

MustCookies is similar to Page.Cookies MustCookies 类似于 Page.Cookies

func (*Page) MustElement

func (p *Page) MustElement(selector string) *Element

MustElement is similar to Page.Element MustElement 类似于 Page.Element

func (*Page) MustElementByJS

func (p *Page) MustElementByJS(js string, params ...interface{}) *Element

MustElementByJS is similar to Page.ElementByJS MustElementByJS 类似于 Page.ElementByJS

func (*Page) MustElementFromNode

func (p *Page) MustElementFromNode(node *proto.DOMNode) *Element

MustElementFromNode 类似于 Page.ElementFromNode

func (*Page) MustElementFromPoint

func (p *Page) MustElementFromPoint(left, top int) *Element

MustElementFromPoint is similar to Page.ElementFromPoint MustElementFromPoint 类似于 Page.ElementFromPoint

func (*Page) MustElementR

func (p *Page) MustElementR(selector, jsRegex string) *Element

MustElementR is similar to Page.ElementR MustElementR 类似于 Page.ElementR

func (*Page) MustElementX

func (p *Page) MustElementX(xPath string) *Element

MustElementX is similar to Page.ElementX MustElementX 类似于 Page.ElementX

func (*Page) MustElements

func (p *Page) MustElements(selector string) Elements

MustElements is similar to Page.Elements MustElements 类似于 Page.Elements

func (*Page) MustElementsByJS

func (p *Page) MustElementsByJS(js string, params ...interface{}) Elements

MustElementsByJS is similar to Page.ElementsByJS MustElementsByJS 类似于 Page.ElementsByJS

func (*Page) MustElementsX

func (p *Page) MustElementsX(xpath string) Elements

MustElementsX is similar to Page.ElementsX MustElementsX 类似于 Page.ElementsX

func (*Page) MustEmulate

func (p *Page) MustEmulate(device devices.Device) *Page

MustEmulate is similar to Page.Emulate MustEmulate 类似于 Page.Emulate

func (*Page) MustEval

func (p *Page) MustEval(js string, params ...interface{}) gson.JSON

MustEval is similar to Page.Eval MustEval 类似于 Page.Eval

func (*Page) MustEvalOnNewDocument

func (p *Page) MustEvalOnNewDocument(js string)

MustEvalOnNewDocument is similar to Page.EvalOnNewDocument MustEvalOnNewDocument 类似于 Page.EvalOnNewDocument

func (*Page) MustEvaluate

func (p *Page) MustEvaluate(opts *EvalOptions) *proto.RuntimeRemoteObject

MustEvaluate is similar to Page.Evaluate MustEvaluate 类似于 Page.Evaluate

func (*Page) MustExpose

func (p *Page) MustExpose(name string, fn func(gson.JSON) (interface{}, error)) (stop func())

MustExpose is similar to Page.Expose MustExpose 类似于 Page.Expose

func (*Page) MustGetWindow

func (p *Page) MustGetWindow() *proto.BrowserBounds

MustGetWindow is similar to Page.GetWindow MustGetWindow 类似于 Page.GetWindow

func (*Page) MustHTML

func (p *Page) MustHTML() string

MustHTML is similar to Page.HTML MustHTML 类似于 Page.HTML

func (*Page) MustHandleDialog

func (p *Page) MustHandleDialog() (wait func() *proto.PageJavascriptDialogOpening, handle func(bool, string))

MustHandleDialog is similar to Page.HandleDialog MustHandleDialog 类似于 Page.HandleDialog

func (*Page) MustHas

func (p *Page) MustHas(selector string) bool

MustHas is similar to Page.Has MustHas 类似于 Page.Has

func (*Page) MustHasR

func (p *Page) MustHasR(selector, regex string) bool

MustHasR is similar to Page.HasR MustHasR 类似于 Page.HasR

func (*Page) MustHasX

func (p *Page) MustHasX(selector string) bool

MustHasX is similar to Page.HasX MustHasX 类似于 Page.HasX

func (*Page) MustInfo

func (p *Page) MustInfo() *proto.TargetTargetInfo

MustInfo is similar to Page.Info MustInfo 类似于 Page.Info

func (*Page) MustInsertText

func (p *Page) MustInsertText(text string) *Page

MustInsertText is similar to Page.InsertText MustInsertText 类似于 Page.InsertText

func (*Page) MustNavigate

func (p *Page) MustNavigate(url string) *Page

MustNavigate is similar to Page.Navigate MustNavigate 类似于 Page.Navigate

func (*Page) MustNavigateBack

func (p *Page) MustNavigateBack() *Page

MustNavigateBack is similar to Page.NavigateBack MustNavigateBack 类似于 Page.NavigateBack

func (*Page) MustNavigateForward

func (p *Page) MustNavigateForward() *Page

MustNavigateForward is similar to Page.NavigateForward MustNavigateForward 类似于 Page.NavigateForward

func (*Page) MustObjectToJSON

func (p *Page) MustObjectToJSON(obj *proto.RuntimeRemoteObject) gson.JSON

MustObjectToJSON is similar to Page.ObjectToJSON MustObjectToJSON 类似于 Page.ObjectToJSON

func (*Page) MustObjectsToJSON

func (p *Page) MustObjectsToJSON(list []*proto.RuntimeRemoteObject) gson.JSON

MustObjectsToJSON is similar to Page.ObjectsToJSON MustObjectsToJSON 类似于 Page.ObjectsToJSON

func (*Page) MustPDF

func (p *Page) MustPDF(toFile ...string) []byte

MustPDF is similar to PDF. MustPDF 类似于 to PDF. If the toFile is "", it Page.will save output to "tmp/pdf" folder, time as the file name. 如果 toFile 是 "" ,将会把截图保存到 "tmp/screenshots" 文件夹,文件以当前时间命名

func (*Page) MustRelease

func (p *Page) MustRelease(obj *proto.RuntimeRemoteObject) *Page

MustRelease is similar to Page.Release MustRelease 类似于 Page.Release

func (*Page) MustReload

func (p *Page) MustReload() *Page

MustReload is similar to Page.Reload MustReload 类似于 Page.Reload

func (*Page) MustScreenshot

func (p *Page) MustScreenshot(toFile ...string) []byte

MustScreenshot is similar to Screenshot. MustScreenshot 类似于 Screenshot. If the toFile is "", it Page.will save output to "tmp/screenshots" folder, time as the file name. 如果 toFile 是 "" ,将会把截图保存到 "tmp/screenshots" 文件夹,文件以当前时间命名

func (*Page) MustScreenshotFullPage

func (p *Page) MustScreenshotFullPage(toFile ...string) []byte

MustScreenshotFullPage is similar to ScreenshotFullPage. MustScreenshotFullPage 类似于 ScreenshotFullPage. If the toFile is "", it Page.will save output to "tmp/screenshots" folder, time as the file name. 如果 toFile 是 "" ,将会把截图保存到 "tmp/screenshots" 文件夹,文件以当前时间命名

func (*Page) MustSearch

func (p *Page) MustSearch(query string) *Element

MustSearch is similar to Page.Search . MustSearch 类似于 Page.Search . It only returns the first element in the search result. 只会返回搜索结果中第一个元素

func (*Page) MustSetCookies

func (p *Page) MustSetCookies(cookies ...*proto.NetworkCookieParam) *Page

MustSetCookies is similar to Page.SetCookies. MustSetCookies 类似于 Page.SetCookies. If the len(cookies) is 0 it will clear all the cookies. 如果 Cookies 的长度是0,将会清空所有 Cookie

func (*Page) MustSetDocumentContent

func (p *Page) MustSetDocumentContent(html string) *Page

MustSetDocumentContent is similar to Page.SetDocumentContent MustSetDocumentContent 类似于 Page.SetDocumentContent

func (*Page) MustSetExtraHeaders

func (p *Page) MustSetExtraHeaders(dict ...string) (cleanup func())

MustSetExtraHeaders is similar to Page.SetExtraHeaders MustSetExtraHeaders 类似于 Page.SetExtraHeaders

func (*Page) MustSetUserAgent

func (p *Page) MustSetUserAgent(req *proto.NetworkSetUserAgentOverride) *Page

MustSetUserAgent is similar to Page.SetUserAgent MustSetUserAgent 类似于 Page.SetUserAgent

func (*Page) MustSetViewport

func (p *Page) MustSetViewport(width, height int, deviceScaleFactor float64, mobile bool) *Page

MustSetViewport is similar to Page.SetViewport MustSetViewport 类似于 Page.SetViewport

func (*Page) MustSetWindow

func (p *Page) MustSetWindow(left, top, width, height int) *Page

MustSetWindow is similar to Page.SetWindow MustSetWindow 类似于 Page.SetWindow

func (*Page) MustStopLoading

func (p *Page) MustStopLoading() *Page

MustStopLoading is similar to Page.StopLoading MustStopLoading 类似于 Page.StopLoading

func (*Page) MustWait

func (p *Page) MustWait(js string, params ...interface{}) *Page

MustWait is similar to Page.Wait MustWait 类似于 Page.Wait

func (*Page) MustWaitElementsMoreThan

func (p *Page) MustWaitElementsMoreThan(selector string, num int) *Page

MustWaitElementsMoreThan is similar to Page.WaitElementsMoreThan MustWaitElementsMoreThan 类似于 Page.WaitElementsMoreThan

func (*Page) MustWaitIdle

func (p *Page) MustWaitIdle() *Page

MustWaitIdle is similar to Page.WaitIdle MustWaitIdle 类似于 Page.WaitIdle

func (*Page) MustWaitLoad

func (p *Page) MustWaitLoad() *Page

MustWaitLoad is similar to Page.WaitLoad MustWaitLoad 类似于 Page.WaitLoad

func (*Page) MustWaitNavigation

func (p *Page) MustWaitNavigation() func()

MustWaitNavigation is similar to Page.WaitNavigation MustWaitNavigation 类似于 Page.WaitNavigation

func (*Page) MustWaitOpen

func (p *Page) MustWaitOpen() (wait func() (newPage *Page))

MustWaitOpen is similar to Page.WaitOpen MustWaitOpen 类似于 Page.WaitOpen

func (*Page) MustWaitRequestIdle

func (p *Page) MustWaitRequestIdle(excludes ...string) (wait func())

MustWaitRequestIdle is similar to Page.WaitRequestIdle MustWaitRequestIdle 类似于 Page.WaitRequestIdle

func (*Page) MustWindowFullscreen

func (p *Page) MustWindowFullscreen() *Page

MustWindowFullscreen is similar to Page.WindowFullscreen MustWindowFullscreen 类似于 Page.WindowFullscreen

func (*Page) MustWindowMaximize

func (p *Page) MustWindowMaximize() *Page

MustWindowMaximize is similar to Page.WindowMaximize MustWindowMaximize 类似于 Page.WindowMaximize

func (*Page) MustWindowMinimize

func (p *Page) MustWindowMinimize() *Page

MustWindowMinimize is similar to Page.WindowMinimize MustWindowMinimize 类似于 Page.WindowMinimize

func (*Page) MustWindowNormal

func (p *Page) MustWindowNormal() *Page

MustWindowNormal is similar to Page.WindowNormal MustWindowNormal 类似于 Page.WindowNormal

func (*Page) Navigate

func (p *Page) Navigate(url string) error

Navigate to the url. If the url is empty, "about:blank" will be used. 导航至 url 地址,如果 url 是空的,则默认使用 "about:blank" It will return immediately after the server responds the http header. 在接收到服务器HTTP响应头后,立即返回。

func (*Page) NavigateBack

func (p *Page) NavigateBack() error

NavigateBack history. 返回到历史页面

func (*Page) NavigateForward

func (p *Page) NavigateForward() error

NavigateForward history. 前进到历史页面

func (*Page) ObjectToJSON

func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) (gson.JSON, error)

ObjectToJSON by object id 通过对象ID将对象转换为JSON

func (*Page) Overlay

func (p *Page) Overlay(left, top, width, height float64, msg string) (remove func())

Overlay a rectangle on the main frame with specified message 在主 Frame 上叠加一个带有指定消息的矩形

func (*Page) PDF

func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error)

PDF prints page as PDF 将页面保存为 PDF

func (*Page) Race

func (p *Page) Race() *RaceContext

Race creates a context to race selectors 为 race 选择器创建了一个 RaceContext

func (*Page) Release

func (p *Page) Release(obj *proto.RuntimeRemoteObject) error

Release the remote object. Usually, you don't need to call it. 释放远程对象。通常情况下,你不需要调用它。 When a page is closed or reloaded, all remote objects will be released automatically. 当一个页面被关闭或重新加载时,所有的远程对象将被自动释放。 It's useful if the page never closes or reloads. 这对于页面从来没有被关闭或者重新加载过是非常有用的。

func (*Page) Reload

func (p *Page) Reload() error

Reload page. 刷新页面

func (*Page) Screenshot

func (p *Page) Screenshot(fullpage bool, req *proto.PageCaptureScreenshot) ([]byte, error)

Screenshot captures the screenshot of current page. 捕获当前页面的截图

func (*Page) Search

func (p *Page) Search(query string) (*SearchResult, error)

Search for the given query in the DOM tree until the result count is not zero, before that it will keep retrying. 在DOM树中搜索给定的查询,直到结果计数不为零,在此之前,它将不断重试。 The query can be plain text or css selector or xpath. 查询可以是纯文本、css选择器或xpath。 It will search nested iframes and shadow doms too. 它也会搜索嵌套的iframes和影子dom。

func (*Page) SetCookies

func (p *Page) SetCookies(cookies []*proto.NetworkCookieParam) error

SetCookies is similar to Browser.SetCookies . SetCookies 类似于 Browser.SetCookies .

func (*Page) SetDocumentContent

func (p *Page) SetDocumentContent(html string) error

SetDocumentContent sets the page document html content 在页面中添加 HTML 内容

func (*Page) SetExtraHeaders

func (p *Page) SetExtraHeaders(dict []string) (func(), error)

SetExtraHeaders whether to always send extra HTTP headers with the requests from this page. SetExtraHeaders 是否总是从这个页面的请求中发送额外的HTTP头信息。用于向页面中的请求添加额外的请求头。

func (*Page) SetUserAgent

func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) error

SetUserAgent (browser brand, accept-language, etc) of the page. 用于设置页面中的UserAgent If req is nil, a default user agent will be used, a typical mac chrome. 如果 req 的值是 nil 将会使用默认的 UserAgent,典型的例如 mac chrome

func (*Page) SetViewport

func (p *Page) SetViewport(params *proto.EmulationSetDeviceMetricsOverride) error

SetViewport overrides the values of device screen dimensions SetViewport覆盖设备屏幕尺寸的值

func (*Page) SetWindow

func (p *Page) SetWindow(bounds *proto.BrowserBounds) error

SetWindow location and size 设置窗口位置和大小

func (*Page) Sleeper

func (p *Page) Sleeper(sleeper func() utils.Sleeper) *Page

Sleeper 为链式子操作返回具有指定Sleeper的克隆

func (*Page) StopLoading

func (p *Page) StopLoading() error

StopLoading forces the page stop navigation and pending resource fetches. 强制停止页面的加载以及资源的请求

func (*Page) String

func (p *Page) String() string

String interface

func (*Page) Timeout

func (p *Page) Timeout(d time.Duration) *Page

Timeout 返回一个克隆,其中包含所有链接子操作的指定总超时

func (*Page) Wait

func (p *Page) Wait(opts *EvalOptions) error

Wait until the js returns true 等待 JS 脚本执行返回 true (JS执行成功)

func (*Page) WaitElementsMoreThan

func (p *Page) WaitElementsMoreThan(selector string, num int) error

WaitElementsMoreThan Wait until there are more than <num> <selector> elements. 判断某个元素在页面上是否出现以及出现的次数

func (*Page) WaitEvent

func (p *Page) WaitEvent(e proto.Event) (wait func())

WaitEvent waits for the next event for one time. It will also load the data into the event object. 等待下一个发生的事件一次。它还会将数据加载到事件对象中。

func (*Page) WaitIdle

func (p *Page) WaitIdle(timeout time.Duration) (err error)

WaitIdle waits until the next window.requestIdleCallback is called. WaitIdle 等待直到 window.requestIdleCallback 被调用

func (*Page) WaitLoad

func (p *Page) WaitLoad() error

WaitLoad waits for the `window.onload` event, it returns immediately if the event is already fired. 等待 `window.load` 事件触发,如果已经被触发,则会立即返回

func (*Page) WaitNavigation

func (p *Page) WaitNavigation(name proto.PageLifecycleEventName) func()

WaitNavigation wait for a page lifecycle event when navigating. WaitNavigation 在导航时等待一个页面生命周期事件。 Usually you will wait for proto.PageLifecycleEventNameNetworkAlmostIdle 通常等待的是:proto.PageLifecycleEventNameNetworkAlmostIdle

func (*Page) WaitOpen

func (p *Page) WaitOpen() func() (*Page, error)

WaitOpen waits for the next new page opened by the current one 等待打开从当前页面打开的新页面

func (*Page) WaitRepaint

func (p *Page) WaitRepaint() error

WaitRepaint waits until the next repaint. WaitRepaint会等待下一次重绘。 Doc: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

func (*Page) WaitRequestIdle

func (p *Page) WaitRequestIdle(d time.Duration, includes, excludes []string) func()

WaitRequestIdle returns a wait function that waits until no request for d duration. WaitRequestIdle 返回一个等待函数,等待持续d时间内没有请求为止。 Be careful, d is not the max wait timeout, it's the least idle time. 注意:d不是最大超时时间,而是最小空闲时间 If you want to set a timeout you can use the "Page.Timeout" function. 如果你想为页面设置超时,请使用:`Page.timeout` 函数 Use the includes and excludes regexp list to filter the requests by their url. 使用includes和excludes regexp列表按请求的url筛选请求

func (*Page) WithCancel

func (p *Page) WithCancel() (*Page, func())

WithCancel 返回带有上下文取消函数的克隆

func (*Page) WithPanic

func (p *Page) WithPanic(fail func(interface{})) *Page

WithPanic returns a page clone with the specified panic function. Withpanic 会返回一个带有指定 panic 函数 Page 的克隆 The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit() or panic inside it. 失败时必须立即停止当前 goroutine 的执行,比如使用 runtime.Goexit() 或在其内部发生 panic。

type PagePool

type PagePool chan *Page

PagePool以线程安全的方式限制同一时间内的页面数量。 使用通道来限制并发性是一种常见的做法,对于rod来说并不特殊。 这个helper程序更像是一个使用Go Channel的例子。 参考: https://golang.org/doc/effective_go#channels

func NewPagePool

func NewPagePool(limit int) PagePool

NewPagePool实例

func (PagePool) Cleanup

func (pp PagePool) Cleanup(iteratee func(*Page))

清理 helper

func (PagePool) Get

func (pp PagePool) Get(create func() *Page) *Page

从池中获取一个页面。使用PagePool.Put来使它以后可以重复使用。

func (PagePool) Put

func (pp PagePool) Put(p *Page)

把一个页面放回池中

type Pages

type Pages []*Page

Pages provides some helpers to deal with page list Pages 提供了一些帮助工具来处理页面列表

func (Pages) Empty

func (ps Pages) Empty() bool

Empty returns true if the list is empty 判断 Pages 是否为空

func (Pages) Find

func (ps Pages) Find(selector string) (*Page, error)

Find the page that has the specified element with the css selector 根据 css selector 在页面中查照指定CSS选择器的元素

func (Pages) FindByURL

func (ps Pages) FindByURL(jsRegex string) (*Page, error)

FindByURL returns the page that has the url that matches the jsRegex 返回具有匹配jsRegex的url的页面

func (Pages) First

func (ps Pages) First() *Page

First returns the first page, if the list is empty returns nil First 返回第一个页面,如果页面列表是空的,则返回nil

func (Pages) Last

func (ps Pages) Last() *Page

Last returns the last page, if the list is empty returns nil Last 返回最后一个页面,如果页面列表是空的,则返回nil

func (Pages) MustFind

func (ps Pages) MustFind(selector string) *Page

MustFind is similar to Browser.Find MustFind 类似于 Browser.Find

func (Pages) MustFindByURL

func (ps Pages) MustFindByURL(regex string) *Page

MustFindByURL is similar to Page.FindByURL MustFindByURL 类似于 Page.FindByURL

type RaceContext

type RaceContext struct {
	// contains filtered or unexported fields
}

RaceContext stores the branches to race 存储了 race 的分支

func (*RaceContext) Do

func (rc *RaceContext) Do() (*Element, error)

Do the race 执行 Trace

func (*RaceContext) Element

func (rc *RaceContext) Element(selector string) *RaceContext

Element the doc is similar to MustElement 类似于 MustElement

func (*RaceContext) ElementByJS

func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext

ElementByJS the doc is similar to MustElementByJS 类似于 MustELementByJS

func (*RaceContext) ElementFunc

func (rc *RaceContext) ElementFunc(fn func(*Page) (*Element, error)) *RaceContext

ElementFunc takes a custom function to determine race success ElementFunc 采用自定义函数确定 race 成功

func (*RaceContext) ElementR

func (rc *RaceContext) ElementR(selector, regex string) *RaceContext

ElementR the doc is similar to ElementR 类似于 ElementR

func (*RaceContext) ElementX

func (rc *RaceContext) ElementX(selector string) *RaceContext

ElementX the doc is similar to ElementX 类似于 ElementX

func (*RaceContext) Handle

func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext

Handle adds a callback function to the most recent chained selector. Handle 为最近的链式选择器添加一个回调函数。 The callback function is run, if the corresponding selector is present first, in the Race condition. 如果相应的选择器首先出现在 trace 条件中,回调函数就会运行。

func (*RaceContext) MustDo

func (rc *RaceContext) MustDo() *Element

MustDo is similar to RaceContext.Do MustDo 类似于 RaceContext.Do

func (*RaceContext) MustElementByJS

func (rc *RaceContext) MustElementByJS(js string, params []interface{}) *RaceContext

MustElementByJS is similar to RaceContext.ElementByJS MustElementByJS 类似于 RaceContext.ElementByJS

func (*RaceContext) MustHandle

func (rc *RaceContext) MustHandle(callback func(*Element)) *RaceContext

MustHandle is similar to RaceContext.Handle MustHandle 类似于 RaceContext.Handle

type SearchResult

type SearchResult struct {
	*proto.DOMPerformSearchResult

	// First element in the search result
	// 在搜索结果中的第一个元素
	First *Element
	// contains filtered or unexported fields
}

SearchResult handler

func (*SearchResult) All

func (s *SearchResult) All() (Elements, error)

All returns all elements 返回所有元素

func (*SearchResult) Get

func (s *SearchResult) Get(i, l int) (Elements, error)

Get l elements at the index of i from the remote search result. 从远程搜索结果中获取索引为i的l个元素。

func (*SearchResult) Release

func (s *SearchResult) Release()

Release the remote search result 释放搜索结果

type SelectorType

type SelectorType string

SelectorType enum 枚举选择器的类型

const (
	// SelectorTypeRegex type
	SelectorTypeRegex SelectorType = "regex"
	// SelectorTypeCSSSector type
	SelectorTypeCSSSector SelectorType = "css-selector"
	// SelectorTypeText type
	SelectorTypeText SelectorType = "text"
)

type StreamReader

type StreamReader struct {
	Offset *int
	// contains filtered or unexported fields
}

浏览器数据流的StreamReader

func NewStreamReader

func NewStreamReader(c proto.Client, h proto.IOStreamHandle) *StreamReader

NewStreamReader实例

func (*StreamReader) Close

func (sr *StreamReader) Close() error

关闭流,丢弃任何临时性的备份存储。

func (*StreamReader) Read

func (sr *StreamReader) Read(p []byte) (n int, err error)

type Touch

type Touch struct {
	// contains filtered or unexported fields
}

Touch presents a touch device, such as a hand with fingers, each finger is a proto.InputTouchPoint. Touch events is stateless, we use the struct here only as a namespace to make the API style unified. Touch 代表一个触摸设备,例如带手指的手,每个手指都是一个原型输入点。 Touch 事件是无状态的,我们在这里只把结构作为命名空间,使API的风格统一。

func (*Touch) Cancel

func (t *Touch) Cancel() error

Cancel touch action 取消触摸操作

func (*Touch) End

func (t *Touch) End() error

End touch action 结束触摸操作

func (*Touch) Move

func (t *Touch) Move(points ...*proto.InputTouchPoint) error

Move touch points. Use the InputTouchPoint.ID (Touch.identifier) to track points. 移动触摸点。使用InputTouchPoint.ID(Touch.identifier)来跟踪点。 Doc: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

func (*Touch) MustCancel

func (t *Touch) MustCancel() *Touch

MustCancel is similar to Touch.Cancel MustCancel 类似于 Touch.Cancel

func (*Touch) MustEnd

func (t *Touch) MustEnd() *Touch

MustEnd is similar to Touch.End MustEnd 类似于 Touch.End

func (*Touch) MustMove

func (t *Touch) MustMove(points ...*proto.InputTouchPoint) *Touch

MustMove is similar to Touch.Move MustMove 类似于 Touch.Move

func (*Touch) MustStart

func (t *Touch) MustStart(points ...*proto.InputTouchPoint) *Touch

MustStart is similar to Touch.Start MustStart 类似于 Touch.Start

func (*Touch) MustTap

func (t *Touch) MustTap(x, y float64) *Touch

MustTap is similar to Touch.Tap MustTap 类似于 Touch.Tap

func (*Touch) Start

func (t *Touch) Start(points ...*proto.InputTouchPoint) error

Start a touch action 开始一个触摸操作

func (*Touch) Tap

func (t *Touch) Tap(x, y float64) error

Tap dispatches a touchstart and touchend event. Tap 触发一个 touchstart 和 touchend 事件

type TraceType

type TraceType string

TraceType for logger 日志的 Trace 类型

const (
	// TraceTypeWaitRequestsIdle type
	TraceTypeWaitRequestsIdle TraceType = "wait requests idle"

	// TraceTypeWaitRequests type
	TraceTypeWaitRequests TraceType = "wait requests"

	// TraceTypeQuery type
	TraceTypeQuery TraceType = "query"

	// TraceTypeWait type
	TraceTypeWait TraceType = "wait"

	// TraceTypeInput type
	TraceTypeInput TraceType = "input"
)

func (TraceType) String

func (t TraceType) String() string

String interface

Directories

Path Synopsis
fixtures
lib
cdp
Package cdp for application layer communication with browser.
Package cdp for application layer communication with browser.
defaults
Package defaults of commonly used options parsed from environment.
Package defaults of commonly used options parsed from environment.
js
launcher
Package launcher for launching browser utils.
Package launcher for launching browser utils.
launcher/rod-manager
A server to help launch browser remotely
A server to help launch browser remotely
proto
Package proto is a lib to encode/decode the data of the cdp protocol.
Package proto is a lib to encode/decode the data of the cdp protocol.
utils/docker
The .github/workflows/docker.yml uses it as an github action and run it like this:
The .github/workflows/docker.yml uses it as an github action and run it like this:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL