开始使用chromedp浏览网页的代码指南

2,064 阅读2分钟

chromedp帮助你快速轻松地翻阅网络,并且 编程在Golang中。如果你曾经使用过SeleniumPhantomJS或其他类似的工具,这个概念对你来说很熟悉。

在这篇文章中,我们将开始使用chromedp,并使用它做一些简单的任务。让我们开始吧。

首先,你必须将chromedp添加到你项目的依赖关系中。它可以像你以前使用的其他golang 包一样完成:

go get -u github.com/chromedp/chromedp

为了开始使用chromedp,你不需要做很多事情!你唯一需要做的是创建一个context ,然后开始使用它:

ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
chromedp.Run(ctx, chromedp.Navigate("https://www.google.com"))

就这样了。相信我,chromedp只是打开了google,即使你还没有看到任何东西!你没有看到浏览器的原因是默认情况下它是以无头模式运行的,正如我所期望的,我们可以改变这种行为。实际上,有一个默认行为的列表,默认情况下会传递给库:

// DefaultExecAllocatorOptions are the ExecAllocator options used by NewContext
// if the given parent context doesn't have an allocator set up. Do not modify
// this global; instead, use NewExecAllocator. See ExampleExecAllocator.
var DefaultExecAllocatorOptions = [...]ExecAllocatorOption{
    NoFirstRun,
    NoDefaultBrowserCheck,
    Headless,

    // After Puppeteer's default behavior.
    Flag("disable-background-networking", true),
    Flag("enable-features", "NetworkService,NetworkServiceInProcess"),
    Flag("disable-background-timer-throttling", true),
    Flag("disable-backgrounding-occluded-windows", true),
    Flag("disable-breakpad", true),
    Flag("disable-client-side-phishing-detection", true),
    Flag("disable-default-apps", true),
    Flag("disable-dev-shm-usage", true),
    Flag("disable-extensions", true),
    Flag("disable-features", "site-per-process,TranslateUI,BlinkGenPropertyTrees"),
    Flag("disable-hang-monitor", true),
    Flag("disable-ipc-flooding-protection", true),
    Flag("disable-popup-blocking", true),
    Flag("disable-prompt-on-repost", true),
    Flag("disable-renderer-backgrounding", true),
    Flag("disable-sync", true),
    Flag("force-color-profile", "srgb"),
    Flag("metrics-recording-only", true),
    Flag("safebrowsing-disable-auto-update", true),
    Flag("enable-automation", true),
    Flag("password-store", "basic"),
    Flag("use-mock-keychain", true),
}

你可以看到,数组中的第三项是无头模式,所以我们可以修改它。让我们来创建我们的配置,以创建一个新的上下文:

opts := append(
  // select all the elements after the third element
    chromedp.DefaultExecAllocatorOptions[3:],
    chromedp.NoFirstRun,
    chromedp.NoDefaultBrowserCheck,
)

最新的步骤是创建一个ExecAllocator并将其作为我们的父级上下文:

parentCtx, _ := chromedp.NewExecAllocator(context.Background(), opts...)
ctx, _ := chromedp.NewContext(parentCtx)

现在,如果你运行该项目,你会看到浏览器打开并导航到谷歌网站。以下是完整的代码:

package main

import (
    "context"
    "fmt"

    "github.com/chromedp/chromedp"
)

func main() {
    opts := append(
        // select all the elements after the third element
        chromedp.DefaultExecAllocatorOptions[3:],
        chromedp.NoFirstRun,
        chromedp.NoDefaultBrowserCheck,
    )
    // create chromedp's context
    parentCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()

    ctx, cancel := chromedp.NewContext(parentCtx)
    defer cancel()

    if err := chromedp.Run(ctx, chromedp.Navigate("https://www.google.com")); err != nil {
        panic(err)
    }

    fmt.Println("I've just saw Google!!!")
}