背景
chromedp
關於chromedp
安裝chromedp
go get -u github.com/chromedp/chromedp
使用例子
關於如何使用官方還有一個項目專門來寫了幾個例子來幫助你們入門,第一次接觸能夠先用官方的例子試一下。可是這裏要注意官方的例子中使用的好多都是在國內被屏蔽的網站,地址:https://github.com/chromedp/examplesgolang
chrome普通模式與chrome headless模式的區別
普通模式
普通模式會在電腦上彈出瀏覽器窗口,能夠在瀏覽器中看到代碼執行的效果,調用完成以後須要關閉掉瀏覽器。chrome
chrome headless模式
go run main.go
如何使用chrome普通模式
chromedp
// Command click is a chromedp example demonstrating how to use a selector to
// click on an element.
package main
import (
"context"
"log"
"time"
"github.com/chromedp/chromedp"
)
func main() {
// 禁用chrome headless
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
// create chrome instance
ctx, cancel := chromedp.NewContext(
allocCtx,
chromedp.WithLogf(log.Printf),
)
defer cancel()
// create a timeout
ctx, cancel = context.WithTimeout(ctx, 15*time.Second)
defer cancel()
// navigate to a page, wait for an element, click
var example string
err := chromedp.Run(ctx,
chromedp.Navigate(`https://golang.org/pkg/time/`),
// wait for footer element is visible (ie, page is loaded)
chromedp.WaitVisible(`body > footer`),
// find and click "Expand All" link
chromedp.Click(`#pkg-examples > div`, chromedp.NodeVisible),
// retrieve the value of the textarea
chromedp.Value(`#example_After .play .input textarea`, &example),
)
if err != nil {
log.Fatal(err)
}
log.Printf("Go's time.After example:\n%s", example)
}