Translated By 飞跃|Fly
包chromedp
是一个高水平的Chrome DevTools协议客户端,它简化了驱动浏览器进行刮擦、单元测试或使用CDP对网页进行分析的过程。
chromedp不需要依赖第三方,完全用Go实现异步Chrome DevTools协议。该软件包包括一些简单的例子。此外,https://github.com/chromedp/examples 包含更复杂的例子。
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
)
func writeHTML(content string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, strings.TrimSpace(content))
})
}
func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`<!doctype html>
<html>
<body>
<div id="content">the content</div>
</body>
</html>`))
defer ts.Close()
const expr = `(function(d, id, v) {
var b = d.querySelector('body');
var el = d.createElement('div');
el.id = id;
el.innerText = v;
b.insertBefore(el, b.childNodes[0]);
})(document, %q, %q);`
var nodes []*cdp.Node
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Nodes(`document`, &nodes, chromedp.ByJSPath),
chromedp.WaitVisible(`#content`),
chromedp.ActionFunc(func(ctx context.Context) error {
s := fmt.Sprintf(expr, "thing", "a new thing!")
_, exp, err := runtime.Evaluate(s).Do(ctx)
if err != nil {
return err
}
if exp != nil {
return exp
}
return nil
}),
chromedp.WaitVisible(`#thing`),
); err != nil {
log.Fatal(err)
}
fmt.Println("Document tree:")
fmt.Print(nodes[0].Dump(" ", " ", false))
}
Output:
Document tree:
#document <Document>
html <DocumentType>
html
head
body
div#thing
#text "a new thing!"
div#content
#text "the content"
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"github.com/chromedp/chromedp"
)
func writeHTML(content string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, strings.TrimSpace(content))
})
}
func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<body>
<p id="content" onclick="changeText()">Original content.</p>
<script>
function changeText() {
document.getElementById("content").textContent = "New content!"
}
</script>
</body>
`))
defer ts.Close()
var outerBefore, outerAfter string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.OuterHTML("#content", &outerBefore, chromedp.ByQuery),
chromedp.Click("#content", chromedp.ByQuery),
chromedp.OuterHTML("#content", &outerAfter, chromedp.ByQuery),
); err != nil {
log.Fatal(err)
}
fmt.Println("OuterHTML before clicking:")
fmt.Println(outerBefore)
fmt.Println("OuterHTML after clicking:")
fmt.Println(outerAfter)
}
Output:
OuterHTML before clicking:
<p id="content" onclick="changeText()">Original content.</p>
OuterHTML after clicking:
<p id="content" onclick="changeText()">New content!</p>
func ButtonLeft(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams
ButtonLeft是一个鼠标动作选项,用来设置被点击的按钮为鼠标左键。
func ButtonMiddle(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams
ButtonMiddle是一个鼠标动作选项,用来设置被点击的按钮为鼠标中键。
func ButtonNone(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams
ButtonNone是一个鼠标动作选项,用于将点击的按钮设置为无(用于鼠标移动)。
func ButtonRight(p *input.DispatchMouseEventParams) *input.DispatchMouseEventParams
ButtonRight是一个鼠标动作选项,用于将点击的按钮设置为鼠标右键。
func ByID(s *Selector)
ByID是一个元素查询选项,通过CSS #id选择一个单一的元素。
类似于在浏览器中调用 document.querySelector(‘#’ + ID) 。
func ByJSPath(s *Selector)
ByJSPath是一个元素查询选项,通过 “JS路径 “值选择元素(如Chrome DevTools用户界面所示)。
允许直接查询DOM元素,否则无法使用其他By*函数检索,如ShadowDOM元素。
注意:不要与一个不受信任的选择器值一起使用,因为任何定义的选择器都会被传递给runtime.Evaluate。
func ByNodeID(s *Selector)
ByNodeID是一个元素查询选项,通过他们的节点ID选择元素。
使用DOM.requestChildNodes来检索具有特定节点ID的元素。
注意:必须与[]cdp.NodeID一起使用。
func ByQueryAll(s *Selector)
ByQueryAll是一个元素查询动作选项,通过DOM.querySelectorAll命令选择元素。
类似于在浏览器中调用document.querySelectorAll()。
func BySearch(s *Selector)
BySearch是一个元素查询选项,通过DOM.performSearch命令来选择元素。它通过纯文本、CSS选择器或XPath查询来匹配节点。
func Cancel(ctx context.Context) error
Cancel会取消一个chromedp上下文,等待其资源被清理,并返回在此过程中遇到的任何错误。
如果该上下文分配了一个浏览器,浏览器将被Cancel优雅地关闭。可以给这个上下文附加一个超时,以确定等待浏览器自己关闭的时间。
tctx, tcancel := context.WithTimeout(ctx, 10 * time.Second)
defer tcancel()
chromedp.Cancel(tctx)
通常情况下,”defer cancel()
“就足以满足大多数使用情况。然而,如果想优雅地关闭浏览器,或捕捉在取消过程中发生的底层错误,取消是更好的选择。
func DisableGPU(a *ExecAllocator)
DisableGPU是禁用GPU进程的命令行选项。
–disable-gpu选项是针对无头模式中的一些bug的临时解决方法。但现在已经不需要了。参考资料。-
func EmulateLandscape(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams)
EmulateLandscape是一个仿真视口选项,用于设置设备视口屏幕方向为横向主模式,角度为90。
func EmulateMobile(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams)
EmulateMobile是一个模拟视口选项,用于切换设备视口以显示为移动设备。
func EmulatePortrait(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams)
EmulatePortrait是一个仿真视口选项,用来设置设备视口屏幕方向为纵向主模式,角度为0。
func EmulateTouch(p1 *emulation.SetDeviceMetricsOverrideParams, p2 *emulation.SetTouchEmulationEnabledParams)
EmulateTouch是一个仿真视口选项,用于启用触摸仿真。
func EvalAsValue(p *runtime.EvaluateParams) *runtime.EvaluateParams
EvalAsValue是一个evaluate选项,它将使经过求值的Javascript表达式将表达式的结果编码为JSON编码的值。
func EvalIgnoreExceptions(p *runtime.EvaluateParams) *runtime.EvaluateParams
EvalIgnoreExceptions是一个evaluate选项,它将导致Javascript求值忽略异常。
func EvalWithCommandLineAPI(p *runtime.EvaluateParams) *runtime.EvaluateParams
EvalWithCommandLineAPI是一个求值选项,用于使DevTools命令行API可用于求值脚本。 有关求值操作如何工作的更多信息,请参见Evaluate。 注意:这不应与不受信任的Javascript一起使用。。
func Headless(a *ExecAllocator)
Headless是在无头模式下运行的命令行选项。在设置无头标志的基础上,它还可以隐藏滚动条和静音。
func IgnoreCertErrors(a *ExecAllocator)
IgnoreCertErrors是一个命令行选项,用于忽略与证书有关的错误。当你需要通过代理访问一个HTTPS网站时,这个选项很有用。
func ListenBrowser(ctx context.Context, fn func(ev interface{}))
ListenBrowser添加了一个函数,每当chromedp上下文收到浏览器事件时,该函数将被调用。注意,这只包括浏览器事件;命令响应和目标事件不包括在内。取消ctx会使监听器不再接收任何事件。
注意,在处理事件时,该函数被同步调用。该函数应不惜一切代价避免阻塞。例如,任何行动必须通过单独的goroutine运行(否则,如果行动发送CDP消息,可能导致死锁)。
func ListenTarget(ctx context.Context, fn func(ev interface{}))
ListenTarget添加了一个函数,每当chromedp上下文收到目标事件时,该函数将被调用。取消ctx会使监听器不再接收任何事件。
注意,在处理事件时,该函数被同步调用。该函数应不惜一切代价避免阻塞。例如,任何行动必须通过单独的goroutine运行(否则,如果行动发送CDP消息,可能导致死锁)。
func NewContext(parent context.Context, opts ...ContextOption) (context.Context, context.CancelFunc)
NewContext从父级上下文创建一个chromedp上下文。父语境的分配器被继承,默认为具有DefaultExecAllocatorOptions的ExecAllocator。
如果父级上下文包含一个已分配的浏览器,子级上下文就会继承它,并且它的第一次运行会在该浏览器上创建一个新的标签。否则,它的第一次运行将分配一个新的浏览器。
取消返回的上下文将关闭一个标签或整个浏览器,这取决于上述的逻辑。要在检查错误的同时取消一个上下文,请看取消。
注意,NewContext不会分配也不会启动一个浏览器;这发生在第一次对上下文使用Run的时候。
func NewExecAllocator(parent context.Context, opts ...ExecAllocatorOption) (context.Context, context.CancelFunc)
NewExecAllocator创建了一个用ExecAllocator设置的新上下文,适合与NewContext一起使用。
func NewRemoteAllocator(parent context.Context, url string) (context.Context, context.CancelFunc)
NewRemoteAllocator创建了一个用RemoteAllocator设置的新上下文,适合与NewContext一起使用。url应该指向浏览器的websocket地址,例如 “ws:/127.0.0.1:$PORT/devtools/browser/…”。如果网址不包含”/devtools/browser/”,它将尝试通过发送请求到 “http://$HOST:$PORT/json/version “来检测正确的网址。
接受以下格式的url。* ws:/127.0.0.1:9222/ * http://127.0.0.1:9222/
但 “ws:/127.0.0.1:9222/devtools/browser/”不被接受。因为它包含”/devtools/browser/”,并将被视为一个有效的websocket调试器URL。
func NoDefaultBrowserCheck(a *ExecAllocator)
NoDefaultBrowserCheck是Chrome的命令行选项,用于禁用默认浏览器检查。
func NoFirstRun(a *ExecAllocator)
NoFirstRun是Chrome的命令行选项,用于禁用首次运行对话框。
func NoSandbox(a *ExecAllocator)
NoSandbox是Chrome的命令行选项,用于禁用沙盒。
func NodeEnabled(s *Selector)
NodeEnabled是一个元素查询选项,等待所有被查询的元素节点被浏览器发送并被启用(即没有 “禁用 “属性)。
func NodeNotPresent(s *Selector)
NodeNotPresent是一个元素查询选项,用于等待,直到没有符合查询的元素出现。
注意:强制要求元素节点的预期数量为0。
func NodeNotVisible(s *Selector)
NodeNotVisible是一个元素查询选项,用于等待所有被查询的元素节点被浏览器发送,并且不可见。
func NodeReady(s *Selector)
NodeReady是一个元素查询选项,用于等待所有被查询的元素节点被浏览器发送。
func NodeSelected(s *Selector)
NodeSelected是一个元素查询选项,用于等待所有被查询的元素节点被浏览器发送并被选中(即具有’selected’属性)。
func NodeVisible(s *Selector)
NodeVisible是一个元素查询选项,用于等待所有被查询的元素节点被浏览器发送并可见。
func Run(ctx context.Context, actions ...Action) error
运行一个针对上下文的动作。提供的上下文必须是一个有效的chromedp上下文,通常通过NewContext创建。
请注意,第一次在一个上下文上调用Run时,将通过Allocator分配一个浏览器。因此,在第一次调用Run时使用上下文超时通常是个坏主意,因为它将停止整个浏览器。
func RunResponse(ctx context.Context, actions ...Action) (*network.Response, error)
RunResponse是Run的一个替代品,它可以用于触发页面导航的动作列表,比如点击链接或按钮。
RunResponse将运行这些动作,并阻断直到页面加载,返回其HTML文档的HTTP响应信息。这对于等待页面准备好,或者捕捉404状态代码来说是很有用的,例如。
注意,如果动作触发了多个导航,只有第一个会被使用。如果动作根本没有触发任何导航,RunResponse将阻塞,直到上下文被取消。
func Targets(ctx context.Context) ([]*target.Info, error)
Targets列出了浏览器中连接到给定上下文的所有目标。
func WaitNewTarget(ctx context.Context, fn func(*target.Info) bool) <-chan target.ID
WaitNewTarget可以用来等待当前目标打开一个新的目标。一旦fn匹配到一个新的未连接的目标,它的目标ID将通过返回的通道发送。
type Action interface {
// Do executes the action using the provided context and frame handler.
Do(context.Context) error
}
Action是一个动作的通用接口,将针对上下文和框架处理程序执行。
func CaptureScreenshot(res *[]byte) Action
CaptureScreenshot是一个捕捉/拍摄当前浏览器视口截图的动作。
它的作用与Chrome中的 “捕获屏幕截图 “命令相同。更多信息请参见Screenshot的行为说明。
参见截图动作,对一个特定的元素进行截图。
参见https://github.com/chromedp/examples 项目中的’screenshot’例子,了解对整个页面进行截图的例子。
func Location(urlstr *string) Action
Location是一个检索文档位置的动作。
func NavigationEntries(currentIndex *int64, entries *[]*page.NavigationEntry) Action
NavigationEntries是一个检索页面的导航历史条目的动作。
func Sleep(d time.Duration) Action
Sleep是一个空的动作,调用time.Sleep,并指定持续时间。
注意:这是一个临时的动作定义,是为了方便起见,将来在其余的动作能够被编写/测试之后,可能会被标记为废弃。
func Stop() Action
Stop是一个停止所有导航和待定资源检索的动作。
func Title(title *string) Action
Title是一个检索文档标题的动作。
type ActionFunc func(context.Context) error
ActionFunc是一个适配器,允许使用普通的func作为一个Action。
func (f ActionFunc) Do(ctx context.Context) error
使用所提供的上下文和框架处理程序执行该函数。
type Allocator interface {
// Allocate creates a new browser. It can be cancelled via the provided
// context, at which point all the resources used by the browser (such
// as temporary directories) will be freed.
Allocate(context.Context, ...BrowserOption) (*Browser, error)
// Wait blocks until an allocator has freed all of its resources.
// Cancelling the allocator context will already perform this operation,
// so normally there's no need to call Wait directly.
Wait()
}
一个Allocator负责创建和管理若干个浏览器。
这个接口抽象出了浏览器进程的实际运行方式。例如,一个Allocator的实现可以重复使用浏览器进程,或者连接到远程机器上已经运行的浏览器。
type Browser struct {
// LostConnection is closed when the websocket connection to Chrome is
// dropped. This can be useful to make sure that Browser's context is
// cancelled (and the handler stopped) once the connection has failed.
LostConnection chan struct{}
// contains filtered or unexported fields
}
Browser是高级别的Chrome DevTools协议浏览器管理器,处理浏览器进程运行器、WebSocket客户端、相关目标以及网络、页面和DOM事件。
func NewBrowser(ctx context.Context, urlstr string, opts ...BrowserOption) (*Browser, error)
NewBrowser创建一个新的浏览器。通常情况下,这个函数不会被直接调用,因为Allocator接口会处理它。
func (b *Browser) Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error
func (b *Browser) Process() *os.Process
Process返回浏览器的进程对象。
当浏览器是用RemoteAllocator分配的时候,它可能是空的。对于监控系统来说,收集浏览器进程的进程指标可能很有用。(例子见https://pkg.go.dev/github.com/prometheus/client_golang/prometheus#NewProcessCollector)
Example:
if process := chromedp.FromContext(ctx).Browser.Process(); process != nil {
fmt.Printf("Browser PID: %v", process.Pid)
}
type BrowserOption = func(*Browser)
BrowserOption是一个浏览器选项。
func WithBrowserDebugf(f func(string, ...interface{})) BrowserOption
WithBrowserDebugf是一个浏览器选项,用于指定一个func来记录实际的websocket消息。
func WithBrowserErrorf(f func(string, ...interface{})) BrowserOption
WithBrowserErrorf是一个浏览器选项,用于指定一个接收错误记录的函数。
func WithConsolef(f func(string, ...interface{})) BrowserOption
WithConsolef是一个浏览器选项,用于指定一个接收chrome日志事件的函数。
注意:NOT YET IMPLEMENTED
。
func WithDialTimeout(d time.Duration) BrowserOption
WithDialTimeout是一个浏览器选项,用于指定拨号浏览器的websocket地址时的超时时间。默认值是10秒;使用零的持续时间来不使用超时。
type CallAction Action
CallAction是使用runtime.CallFunctionOn调用Javascript函数的动作。CallAction是使用runtime.CallFunctionOn调用Javascript函数的动作。
func CallFunctionOn(functionDeclaration string, res interface{}, opt CallOption, args ...interface{}) CallAction
CallFunctionOn是一个调用Javascript函数的动作,将函数的结果解密到res。
对res的处理与Evaluate的处理相同。
不要在runtime.CallFunctionOnParams上调用以下方法: – WithReturnByValue:它将根据res的类型来设置; – WithArguments:用args来代替传递参数。
注意:遇到的任何异常都将作为错误返回。
type CallOption = func(params *runtime.CallFunctionOnParams) *runtime.CallFunctionOnParams
CallOption是一个函数,用于修改runtime.CallFunctionOnParams,以提供更多信息。
type Conn struct { // contains filtered or unexported fields }
Conn用gobwas/ws websocket连接实现Transport。
func DialContext(ctx context.Context, urlstr string, opts ...DialOption) (*Conn, error)
DialContext使用gobwas/ws拨打指定的websocket URL。
func (c *Conn) Close() error
Close满足io.Closer接口。
func (c *Conn) Read(_ context.Context, msg *cdproto.Message) error
Read 阅读下一条信息。
func (c *Conn) Write(_ context.Context, msg *cdproto.Message) error
Write 写消息。
type Context struct { // Allocator is used to create new browsers. It is inherited from the // parent context when using NewContext. Allocator Allocator // Browser is the browser being used in the context. It is inherited // from the parent context when using NewContext. Browser *Browser // Target is the target to run actions (commands) against. It is not // inherited from the parent context, and typically each context will // have its own unique Target pointing to a separate browser tab (page). Target *Target // contains filtered or unexported fields }
Context被附加到任何与Run.Context一起使用的有效的Context上。
func FromContext(ctx context.Context) *Context
FromContext提取存储在Context.Context内的数据。
type ContextOption = func(*Context)
ContextOption是一个上下文选项。
func WithBrowserOption(opts ...BrowserOption) ContextOption
WithBrowserOption允许在分配一个新的浏览器时向分配器传递一些浏览器选项。因此,这个上下文选项只能在NewContext分配一个新的浏览器时使用。
func WithDebugf(f func(string, ...interface{})) ContextOption
WithDebugf是WithBrowserOption(WithBrowserDebugf(f))的一个快捷键。
func WithErrorf(f func(string, ...interface{})) ContextOption
WithErrorf是WithBrowserOption(WithBrowserErrorf(f))的一个快捷方式。
func WithLogf(f func(string, ...interface{})) ContextOption
WithLogf是WithBrowserOption(WithBrowserLogf(f))的一个快捷键。
func WithTargetID(id target.ID) ContextOption
WithTargetID设置了一个上下文,使之与现有的目标相连,而不是创建一个新的目标。
type Device interface { // Device returns the device info. Device() device.Info }
Device是已知设备类型的共享接口。
参见:github.com/chromedp/chromedp/device,了解一组现成的设备和模式。
type DialOption = func(*Conn)
DialOption是一个拨号选项。
func WithConnDebugf(f func(string, ...interface{})) DialOption
WithConnDebugf是一个拨号选项,用于设置协议记录器。
type EmulateAction Action
EmulateAction是改变浏览器仿真设置的动作。
func Emulate(device Device) EmulateAction
Emulate 是一个模拟特定设备的动作。
参见:github.com/chromedp/chromedp/device,了解一组现成的设备和模式。
func EmulateReset() EmulateAction
EmulateReset是一个重置设备模拟的动作。
将浏览器的视口、屏幕方向、用户代理和移动/触摸仿真设置重置为浏览器启动时的原始值。
func EmulateViewport(width, height int64, opts ...EmulateViewportOption) EmulateAction
EmulateViewport是一个改变浏览器视口的动作。
包裹了对emulation.SetDeviceMetricsOverride和emulation.SetTouchEmulationEnabled的调用。
注意:这具有将屏幕方向设置/强制为横向的效果,并将默认禁用移动和触摸仿真。如果这不是想要的行为,可以分别使用仿真视口选项EmulateOrientation(或EmulateLandscape/EmulatePortrait)、EmulateMobile和EmulateTouch。
func FullScreenshot(res *[]byte, quality int) EmulateAction
FullScreenshot能以指定的图像质量对整个浏览器视口进行全屏截图。
它的作用应该与Chrome中的 “捕获全尺寸屏幕截图 “命令相同。更多信息请参见Screenshot的行为说明。
压缩质量的有效范围是[0…100]。当这个值为100时,图像格式为png;否则,图像格式为jpeg。
func ResetViewport() EmulateAction
ResetViewport是一个将浏览器视口重置为浏览器启动时的默认值的动作。
注意:不会修改/改变浏览器的模拟用户代理,如果有的话。
type EmulateViewportOption = func(*emulation.SetDeviceMetricsOverrideParams, *emulation.SetTouchEmulationEnabledParams)
EmulateViewportOption是模拟视口选项的类型。
func EmulateOrientation(orientation emulation.OrientationType, angle int64) EmulateViewportOption
EmulateOrientation是一个仿真视口选项,用于设置设备视口屏幕方向。EmulateOrientation是一个仿真视口选项,用于设置设备视口屏幕方向。
func EmulateScale(scale float64) EmulateViewportOption
EmulateScale是一个仿真视口选项,用来设置设备视口的缩放系数。
type Error string
Error是一个chromedp错误。
const ( // ErrInvalidWebsocketMessage is the invalid websocket message. ErrInvalidWebsocketMessage Error = "invalid websocket message" // ErrInvalidDimensions is the invalid dimensions error. ErrInvalidDimensions Error = "invalid dimensions" // ErrNoResults is the no results error. ErrNoResults Error = "no results" // ErrHasResults is the has results error. ErrHasResults Error = "has results" // ErrNotVisible is the not visible error. ErrNotVisible Error = "not visible" // ErrVisible is the visible error. ErrVisible Error = "visible" // ErrDisabled is the disabled error. ErrDisabled Error = "disabled" // ErrNotSelected is the not selected error. ErrNotSelected Error = "not selected" // ErrInvalidBoxModel is the invalid box model error. ErrInvalidBoxModel Error = "invalid box model" // ErrChannelClosed is the channel closed error. ErrChannelClosed Error = "channel closed" // ErrInvalidTarget is the invalid target error. ErrInvalidTarget Error = "invalid target" // ErrInvalidContext is the invalid context error. ErrInvalidContext Error = "invalid context" // ErrPollingTimeout is the error that the timeout reached before the pageFunction returns a truthy value. ErrPollingTimeout Error = "waiting for function failed: timeout" )
错误类型。
func (err Error) Error() string
Error 满足了错误接口。
type EvaluateAction Action
EvaluateAction是使用runtime.Evaluate计算Javascript表达式的动作。
func Evaluate(expression string, res interface{}, opts ...EvaluateOption) EvaluateAction
Evaluate是一个对Javascript表达式求值的操作,将求值的结果解封到res。
当res为nil时,脚本的结果将被忽略。
当res为*[]字节时,脚本结果的原始JSON编码值将被放在res中。
当res是一个**runtime.RemoteObject时,res将被设置为低级协议类型,并且不会尝试转换结果。原始对象会被保留在内存中,直到页面被导航或关闭,除非它们被明确释放或与它们的对象组中的其他对象一起被释放。 runtime.ReleaseObject或runtime.ReleaseObjectGroup可以被用来要求浏览器释放原始对象。
对于所有其他情况,脚本的结果将被 “按值 “返回(即JSON编码),随后将尝试json.Unmarshal脚本的结果到res。如果在这种情况下脚本结果是 “未定义的”,它会返回一个错误。
注意:遇到的任何异常都将作为一个错误返回。
func EvaluateAsDevTools(expression string, res interface{}, opts ...EvaluateOption) EvaluateAction
EvaluateAsDevTools是一个操作,它像Chrome DevTools那样计算Javascript表达式,在“console”上下文中计算表达式,并使脚本可以使用命令行API。 有关如何计算脚本表达式的详细信息,请参见“Evaluate”。 注意:这不应与不受信任的Javascript一起使用。
type EvaluateOption = func(*runtime.EvaluateParams) *runtime.EvaluateParams
EvaluateOption是Javascript计算选项的类型。
func EvalObjectGroup(objectGroup string) EvaluateOption
EvalObjectGroup是用于设置对象组的求值选项。。
type ExecAllocator struct { // contains filtered or unexported fields }
ExecAllocator是一个分配器,它在主机上启动新的浏览器进程。
func (a *ExecAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*Browser, error)
Allocate满足了Allocator接口。
func (a *ExecAllocator) Wait()
等待满足了Allocator接口。
type ExecAllocatorOption = func(*ExecAllocator)
ExecAllocatorOption是一个exec分配器选项。
func CombinedOutput(w io.Writer) ExecAllocatorOption
CombinedOutput用于设置一个io.Writer,来自浏览器的stdout和stderr将被发送到这里。
func Env(vars ...string) ExecAllocatorOption
Env是一个通用环境变量列表,以NAME=value的形式传递给新的Chrome进程。这些变量将被附加到由os.Environ检索到的golang进程的环境中。
func ExecPath(path string) ExecAllocatorOption
ExecPath返回一个ExecAllocatorOption,它使用给定的路径来执行浏览器进程。给定的路径可以是一个二进制文件的绝对路径,或者只是通过exec.LookPath查找的程序名称。
func Flag(name string, value interface{}) ExecAllocatorOption
Flag是一个通用的命令行选项,用于向Chrome传递一个标志。如果值是一个字符串,它将以--name=value
的形式传递。如果它是一个布尔值,如果值为真,它将作为--name
传递。
func ModifyCmdFunc(f func(cmd *exec.Cmd)) ExecAllocatorOption
ModifyCmdFunc允许在浏览器exec.Cmd对象上运行一个任意的函数。这取代了默认版本的命令,该命令在Go程序退出时向任何打开的浏览器发送SIGKILL。
func ProxyServer(proxy string) ExecAllocatorOption
ProxyServer是命令行选项,用于设置出站代理服务器。
func UserAgent(userAgent string) ExecAllocatorOption
UserAgent是命令行选项,用于设置默认的User-Agent头。
func UserDataDir(dir string) ExecAllocatorOption
UserDataDir是用于设置用户数据目录的命令行选项。
注意:设置该选项可以手动设置Chrome浏览器使用的配置文件目录。如果没有设置,那么将在/tmp目录下创建一个默认路径。
func WindowSize(width, height int) ExecAllocatorOption
WindowSize是命令行选项,用于设置初始窗口尺寸。
type KeyAction Action
KeyAction是键盘(键)输入事件动作。
func KeyEvent(keys string, opts ...KeyOption) KeyAction
KeyEvent是一个按键动作,为按键中包含的每个符文以及任何提供的按键选项合成一个keyDown、char和keyUp事件。
只有众所周知的、”printable “的字符才会有char事件的合成。
参见SendKeys动作,为一个特定的元素节点合成按键事件。
参见chromedp/kb包的实现细节和知名的键的列表。
func KeyEventNode(n *cdp.Node, keys string, opts ...KeyOption) KeyAction
KeyEventNode是一个按键动作,在一个元素节点上派发一个按键事件。
type KeyOption = func(*input.DispatchKeyEventParams) *input.DispatchKeyEventParams
KeyOption是一个钥匙动作选项。
func KeyModifiers(modifiers ...input.Modifier) KeyOption
KeyModifiers是一个按键动作选项,用于在按键上添加额外的修改器。
type MouseAction Action
MouseAction是鼠标输入事件动作
func MouseClickNode(n *cdp.Node, opts ...MouseOption) MouseAction
MouseClickNode是一个动作,它在指定节点的中心派发一个鼠标左键点击事件。
注意,如果节点不在窗口的视口内,窗口将被滚动。
func MouseClickXY(x, y float64, opts ...MouseOption) MouseAction
MouseClickXY是一个将鼠标左键点击(即mousePressed和mouseReleased事件)发送至X、Y位置的动作。
func MouseEvent(typ input.MouseType, x, y float64, opts ...MouseOption) MouseAction
MouseEvent是一个鼠标事件动作,在坐标x, y处派发指定的鼠标事件类型。
type MouseOption = func(*input.DispatchMouseEventParams) *input.DispatchMouseEventParams
MouseOption是一个鼠标动作选项。
func Button(btn string) MouseOption
Button是一个鼠标动作选项,用于从一个字符串中设置要点击的按钮。
func ButtonModifiers(modifiers ...input.Modifier) MouseOption
ButtonModifiers是一个鼠标动作选项,用于为按钮点击添加额外的输入修改器。
func ButtonType(button input.MouseButton) MouseOption
ButtonType is a mouse action option to set the button to click.
func ClickCount(n int) MouseOption
ClickCount是一个鼠标动作选项,用于设置点击次数。
NavigateAction是总是触发页面导航的动作,等待页面加载。
请注意,这些动作不收集HTTP响应信息;关于这一点,请参阅RunResponse。
func Navigate(urlstr string) NavigateAction
Navigate是一个导航当前帧的动作。
func NavigateBack() NavigateAction
NavigateBack是一个在历史中向后导航当前帧的动作。
func NavigateForward() NavigateAction
NavigateForward是一个在历史中向前导航当前帧的动作。
func NavigateToHistoryEntry(entryID int64) NavigateAction
NavigateToHistoryEntry是一个动作,用于导航到指定的导航条目。
func Reload() NavigateAction
Reload是一个重新加载当前页面的动作。
type PollAction Action
PollAction是将等待一般Javascript断言的Action。
关于构建轮询任务的细节,请参见轮询。
func Poll(expression string, res interface{}, opts ...PollOption) PollAction
轮询是一个轮询Action,它将等待一个普通的Javascript断言。它从一个Javascript表达式构建断言。
这是puppeteer的page.waitForFunction的副本。见https://github.com/puppeteer/puppeteer/blob/v8.0.0/docs/api.md#pagewaitforfunctionpagefunction-options-args。它被有意命名为Poll,以避免与Wait*查询动作相混淆。该行为不保证是兼容的。例如,我们的实现使轮询任务不能从导航中存活下来,在这种情况下会引发一个错误(见单元测试TestPoll/NotSurviveNavigation)。
默认的轮询模式是 “raf”,在requestAnimationFrame回调中不断执行pageFunction。这是最严格的轮询模式,适合观察造型变化。WithPollingInterval选项使其以指定的时间间隔轮询断言。WithPollingMutation选项使其在每次DOM变异时轮询断言。
WithPollingTimeout选项指定了等待predicate返回真值的最长时间。它的默认值是30秒。通过0来禁用超时。
WithPollingFrame选项指定要在其中计算断言的Frame。如果未指定,将在当前选项卡的根页中对其求值。
WithPollingArgs选项提供额外的参数以传递给断言。只有当predicate是由函数建立的时候才应用这个选项。参见PollFunction。
func PollFunction(pageFunction string, res interface{}, opts ...PollOption) PollAction
PollFunction是一个轮询动作,它将等待一个普通的Javascript断言。它从一个Javascript函数建立谓词。
关于构建轮询任务的细节,请参见Poll。
type PollOption = func(task *pollTask)
PollOption是一个轮询任务选项。
func WithPollingArgs(args ...interface{}) PollOption
WithPollingArgs提供了额外的参数来传递给断言。
func WithPollingInFrame(frame *cdp.Node) PollOption
WithPollingFrame选项指定要在其中计算断言的Frame。如果未指定,将在当前选项卡的根页中对其求值。
func WithPollingInterval(interval time.Duration) PollOption
WithPollingInterval使其以指定的时间间隔轮询断言。
func WithPollingMutation() PollOption
WithPollingMutation使得它在每次DOM突变时都要轮询断言。
func WithPollingTimeout(timeout time.Duration) PollOption
WithPollingTimeout指定了等待谓词返回真值的最长时间。它的默认值是30秒。通过0来禁用超时。
type QueryAction Action
QueryAction是元素查询动作,从浏览器的DOM中选择节点元素进行检索或操作。
关于构建元素查询选择器的细节,请参见查询。
func AttributeValue(sel interface{}, name string, value *string, ok *bool, opts ...QueryOption) QueryAction
AttributeValue是一个元素查询动作,检索与选择器匹配的第一个元素节点的元素属性值。
func Attributes(sel interface{}, attributes *map[string]string, opts ...QueryOption) QueryAction
Attributes是一个元素查询动作,检索与选择器匹配的第一个元素节点的元素属性。
func AttributesAll(sel interface{}, attributes *[]map[string]string, opts ...QueryOption) QueryAction
AttributesAll是一个元素查询动作,它检索所有匹配选择器的元素节点的元素属性。
注意:这应该和ByQueryAll查询选项一起使用。
func Blur(sel interface{}, opts ...QueryOption) QueryAction
Blur是一个元素查询动作,它取消了与选择器匹配的第一个元素节点的焦点(Blur)。
func Clear(sel interface{}, opts ...QueryOption) QueryAction
Clear是一个元素查询动作,清除任何与选择器匹配的输入/textarea元素节点的值。
func Click(sel interface{}, opts ...QueryOption) QueryAction
Click是一个元素查询动作,它向与选择器相匹配的第一个元素节点发送一个鼠标点击事件。
func ComputedStyle(sel interface{}, style *[]*css.ComputedStyleProperty, opts ...QueryOption) QueryAction
ComputedStyle是一个元素查询动作,检索匹配选择器的第一个元素节点的计算样式。
func Dimensions(sel interface{}, model **dom.BoxModel, opts ...QueryOption) QueryAction
Dimensions是一个元素查询动作,检索匹配选择器的第一个元素节点的箱体模型尺寸。
func DoubleClick(sel interface{}, opts ...QueryOption) QueryAction
DoubleClick是一个元素查询动作,将鼠标双击事件发送到与选择器匹配的第一个元素节点。
func Focus(sel interface{}, opts ...QueryOption) QueryAction
Focus是一个元素查询动作,聚焦于与选择器匹配的第一个元素节点。
func InnerHTML(sel interface{}, html *string, opts ...QueryOption) QueryAction
InnerHTML是一个元素查询动作,检索与选择器匹配的第一个元素节点的内部HTML。
func JavascriptAttribute(sel interface{}, name string, res interface{}, opts ...QueryOption) QueryAction
JavascriptAttribute是一个元素查询动作,它为第一个匹配选择器的元素节点检索Javascript属性。
func MatchedStyle(sel interface{}, style **css.GetMatchedStylesForNodeReturns, opts ...QueryOption) QueryAction
MatchedStyle是一个元素查询动作,它检索匹配选择器的第一个元素节点的匹配样式信息。
func NodeIDs(sel interface{}, ids *[]cdp.NodeID, opts ...QueryOption) QueryAction
NodeIDs是一个元素查询动作,检索与选择器匹配的元素节点ID。
func Nodes(sel interface{}, nodes *[]*cdp.Node, opts ...QueryOption) QueryAction
Nodes是一个元素查询动作,检索与选择器匹配的文档元素节点。
func OuterHTML(sel interface{}, html *string, opts ...QueryOption) QueryAction
OuterHTML是一个元素查询动作,检索匹配选择器的第一个元素节点的外部HTML。
func Query(sel interface{}, opts ...QueryOption) QueryAction
Query是一个查询动作,用于查询浏览器中符合标准的特定元素节点。
以浏览器DOM元素节点(或多个节点)为目标的查询动作,结合After选项(见下文)使用Query,以检索数据或修改查询所选的元素。
Example:
chromedp.Run(ctx, chromedp.SendKeys(`thing`, chromedp.ByID))
上述内容将对符合浏览器CSS查询 “#thing “的第一个元素执行 “SendKeys “操作。
元素选择查询与特定的动作结合使用,是在浏览器中实现任务自动化的主要方式。它们通常被写成以下形式。
Action(selector[, parameter1, ...parameterN][,result][, queryOptions...])
Where:
Action - the action to perform selector - element query selection (typically a string), that any matching node(s) will have the action applied parameter[1-N] - parameter(s) needed for the individual action (if any) result - pointer to a result (if any) queryOptions - changes how queries are executed, or how nodes are waited for (see below)
By* 选项指定了浏览器用于执行选择查询的元素查询的类型。如果没有指定,元素查询将使用BySearch(DOM.performSearch的封装器)。
Node* 选项指定节点条件,导致查询等待,直到指定条件为真。当没有指定时,查询将使用NodeReady等待条件。
AtLeast选项改变了必须由元素查询返回的最小节点数。如果没有指定,默认值是1。
After选项用于指定一个函数,当元素查询返回一个或多个元素后,在节点条件为真时,该函数将被执行。
BySearch(默认)选项可以通过纯文本、CSS选择器或XPath查询来查询元素,包裹DOM.performSearch。
ByID选项可以通过匹配的CSS ID来查询单个元素,包裹DOM.querySelector。ByID类似于在浏览器中调用document.querySelector(‘#’ + ID)。
ByQuery选项可以用一个CSS选择器来查询单个元素,包裹DOM.querySelector。ByQuery类似于在浏览器中调用document.querySelector()。
ByQueryAll选项可以使用一个CSS选择器来查询元素,包裹DOM.querySelectorAll。ByQueryAll类似于在浏览器中调用document.querySelectorAll()。
ByJSPath选项可以使用其 “JS路径 “值查询单个元素,包裹Runtime.evaluation。ByJSPath类似于执行一个Javascript片段,从浏览器中返回一个元素。ByJSPath应该只用于可信的元素查询,因为它被直接传递给Runtime.evaluate,并且没有尝试对查询进行消毒。对于查询不能用其他By*函数检索的DOM元素很有用,比如ShadowDOM元素。
NodeReady(默认)选项导致查询等待,直到所有与选择器匹配的元素节点被从浏览器中检索出来。
NodeVisible选项使查询等待,直到所有与选择器匹配的元素节点被从浏览器中检索出来,并且是可见的。
NodeNotVisible选项使查询等待,直到所有与选择器匹配的元素节点被从浏览器中检索出来,并且不可见。
NodeEnabled选项导致查询等待,直到所有匹配选择器的元素节点被从浏览器中检索出来,并且是启用的(即没有 “禁用 “属性)。
NodeSelected选项导致查询等待,直到所有匹配选择器的元素节点被从浏览器中检索出来,并且被选中(即有一个’selected’属性)。
NodeNotPresent选项导致查询等待,直到没有匹配选择器的元素节点。
func QueryAfter(sel interface{}, f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error, opts ...QueryOption) QueryAction
QueryAfter是一个元素查询动作,查询浏览器的选择器sel。等待,直到查询的可见性条件得到满足,之后执行f。
func RemoveAttribute(sel interface{}, name string, opts ...QueryOption) QueryAction
RemoveAttribute是一个元素查询动作,从第一个匹配选择器的元素节点上删除带有名称的元素属性。
func Reset(sel interface{}, opts ...QueryOption) QueryAction
Reset是一个元素查询动作,重置第一个匹配选择器的元素节点的父节点形式。
func Screenshot(sel interface{}, picbuf *[]byte, opts ...QueryOption) QueryAction
Screenshot是一个元素查询动作,它对与选择器相匹配的第一个元素节点进行截图。
它的作用应该与Chrome中的 “捕获节点截图 “命令相同。
行为说明:协议监视器显示,该命令也会发送以下CDP命令:
- Emulation.clearDeviceMetricsOverride - Network.setUserAgentOverride with {"userAgent": ""} - Overlay.setShowViewportSizeOnResize with {"show": false}
这些CDP命令不是由chromedp发送的。如果没有达到预期效果,你可以尝试自己发送这些命令。
参见CaptureScreenshot,用于捕获浏览器视口的屏幕截图。
参见https://github.com/chromedp/examples 项目中的’screenshot’例子,了解对整个页面进行截图的例子。
func ScrollIntoView(sel interface{}, opts ...QueryOption) QueryAction
ScrollIntoView是一个元素查询动作,将窗口滚动到与选择器匹配的第一个元素节点。
func SendKeys(sel interface{}, v string, opts ...QueryOption) QueryAction
SendKeys是一个元素查询动作,它根据v中的符文的需要,合成按键向上、char和向下的事件,将它们发送到与选择器匹配的第一个元素节点。
关于如何使用SendKeys的完整例子,见https://github.com/chromedp/examples/tree/master/keys。
注意:当元素查询匹配一个input[type=”file”]节点时,则使用dom.SetFileInputFiles来设置输入节点的上传路径到v。
func SetAttributeValue(sel interface{}, name, value string, opts ...QueryOption) QueryAction
SetAttributeValue是一个元素查询动作,它为匹配选择器的第一个元素节点将带有名称的元素属性设置为值。
func SetAttributes(sel interface{}, attributes map[string]string, opts ...QueryOption) QueryAction
SetAttributes是一个元素查询动作,为匹配选择器的第一个元素节点设置元素属性。
func SetJavascriptAttribute(sel interface{}, name, value string, opts ...QueryOption) QueryAction
SetJavascriptAttribute是一个元素查询动作,为匹配选择器的第一个元素节点设置Javascript属性。
func SetUploadFiles(sel interface{}, files []string, opts ...QueryOption) QueryAction
SetUploadFiles是一个元素查询动作,为匹配选择器的第一个元素节点设置要上传的文件(即为input[type=”file”] 节点)。
func SetValue(sel interface{}, value string, opts ...QueryOption) QueryAction
SetValue是一个元素查询动作,设置第一个匹配选择器的元素节点的Javascript值。
对于设置一个元素的Javascript值很有用,即表单、输入、文本区域、选择或其他有’.value’字段的元素。
func Submit(sel interface{}, opts ...QueryOption) QueryAction
Submit是一个元素查询动作,提交匹配选择器的第一个元素节点的父表单。
func Text(sel interface{}, text *string, opts ...QueryOption) QueryAction
Text是一个元素查询动作,检索匹配选择器的第一个元素节点的可见文本。
func TextContent(sel interface{}, text *string, opts ...QueryOption) QueryAction
TextContent是一个元素查询动作,检索与选择器匹配的第一个元素节点的文本内容。
func Value(sel interface{}, value *string, opts ...QueryOption) QueryAction
Value是一个元素查询动作,检索与选择器匹配的第一个元素节点的Javascript值域。
对于检索一个元素的Javascript值很有用,即form、input、textarea、select或任何其他有’.value’字段的元素。
func WaitEnabled(sel interface{}, opts ...QueryOption) QueryAction
WaitEnabled是一个元素查询动作,它等到匹配选择器的元素被启用(即没有属性’disabled’)。
func WaitNotPresent(sel interface{}, opts ...QueryOption) QueryAction
WaitNotPresent是一个元素查询动作,等待直到没有匹配选择器的元素出现。
func WaitNotVisible(sel interface{}, opts ...QueryOption) QueryAction
WaitNotVisible是一个元素查询动作,它一直等到与选择器匹配的元素不可见为止。
func WaitReady(sel interface{}, opts ...QueryOption) QueryAction
WaitReady是一个元素查询动作,它等到与选择器匹配的元素准备好了(即已经 “加载”)。
func WaitSelected(sel interface{}, opts ...QueryOption) QueryAction
WaitSelected是一个元素查询动作,它等到与选择器匹配的元素被选中(即有属性’selected’)。
func WaitVisible(sel interface{}, opts ...QueryOption) QueryAction
WaitVisible是一个元素查询动作,它要等到与选择器相匹配的元素是可见的。
type QueryOption = func(*Selector)
QueryOption是一个元素查询动作选项。
func After(f func(context.Context, runtime.ExecutionContextID, ...*cdp.Node) error) QueryOption
After是一个元素查询选项,它设置了一个函数,在浏览器返回匹配的节点后,在节点条件为真后执行。
func AtLeast(n int) QueryOption
AtLeast是一个元素查询选项,用于设置查询必须返回的最小元素数。
默认情况下,一个查询将有一个1的值。
func ByFunc(f func(context.Context, *cdp.Node) ([]cdp.NodeID, error)) QueryOption
ByFunc是一个元素查询动作选项,用于设置用于选择元素的func。
func FromNode(node *cdp.Node) QueryOption
FromNode是一个元素查询动作选项,它将运行一个查询。也就是说,该查询将只查看节点的元素子树。默认情况下,或者当传递nil时,将使用文档的根元素。
注意,目前 BySearch 和 ByJSPath 不支持 FromNode;这个选项主要对 ByQuery 选择器有用。
func WaitFunc(wait func(context.Context, *cdp.Frame, runtime.ExecutionContextID, ...cdp.NodeID) ([]*cdp.Node, error)) QueryOption
WaitFunc是一个元素查询选项,用于设置自定义节点条件等待。
type RemoteAllocator struct { // contains filtered or unexported fields }
远程分配器(RemoteAllocator)是一个分配器,它通过websocket URL连接到一个已经运行的Chrome进程。
func (a *RemoteAllocator) Allocate(ctx context.Context, opts ...BrowserOption) (*Browser, error)
Allocate满足了Allocator接口。
func (a *RemoteAllocator) Wait()
Wait 满足了的Allocator接口。
type Selector struct { // contains filtered or unexported fields }
选择器持有与一个元素选择查询有关的信息。
关于建立一个元素选择器和相关选项的信息,见Query。
func (s *Selector) Do(ctx context.Context) error
Do执行选择器,只有在选择器的by、wait和after函数成功,或者上下文被取消的情况下才结束。
type Target struct { SessionID target.SessionID TargetID target.ID // contains filtered or unexported fields }
Target 管理一个Chrome DevTools协议目标。
func (t *Target) Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error
type Tasks []Action
Task 是一个连续的Action列表,可以作为一个单一的Action来使用。
func (t Tasks) Do(ctx context.Context) error
Do使用提供的上下文和框架处理程序,按顺序执行行动列表。
type Transport interface { Read(context.Context, *cdproto.Message) error Write(context.Context, *cdproto.Message) error io.Closer }
Tansport 是向目标发送/接收消息的通用接口。
这个接口目前是由Browser内部使用的,但它被公开了,因为它在未来作为公共API的一部分会很有用。