LoginSignup
9
6

More than 5 years have passed since last update.

Chrome の Headless モード (Golang)

Posted at
chrome_headless.go
// ---------------------------------------------------------------
//
//  chrome_headless.go
//
//                  Sep/26/2018
// ---------------------------------------------------------------
package main

import (
    "github.com/sclevine/agouti"
    "fmt"
    "os"
    "log"
    "io/ioutil"
    "time"
)

// ---------------------------------------------------------------
func main() {
    fmt.Fprintf (os.Stderr,"*** 開始 ***\n")

    url := "https://ekzemplaro.org/storytelling"

    driver := agouti.ChromeDriver(
        agouti.ChromeOptions("args", []string{
        "--headless",
        }),
        agouti.Debug,
        )

    err := driver.Start() 
    if err != nil {
        log.Printf("Failed to start driver: %v", err)
    }

    page, err := driver.NewPage(agouti.Browser("chrome"))
    if err != nil {
        log.Printf("Failed to open page: %v", err)
    }

    err = page.Navigate(url)
    if err != nil {
        log.Printf("Failed to navigate: %v", err)
    }

    fmt.Printf(page.Title())
    fmt.Printf("\n")

    html, err := page.HTML()
    fmt.Printf (html)
    fmt.Printf("\n")

    time.Sleep(100 * time.Millisecond)

    out_filename := "tmp001.html"
    ioutil.WriteFile (out_filename,[]byte(html),0666)

    fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}

// ---------------------------------------------------------------
Makefile
chrome_headless: chrome_headless.go
    go build chrome_headless.go
clean:
    rm -f chrome_headless

コンパイル

$ make
go build chrome_headless.go

実行方法

export PATH=/opt/chromedriver:$PATH
./chrome_headless
9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6