log

日記です

go selenium memo

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/pkg/errors"
	"github.com/sclevine/agouti"
)

// how to setup
// brew update
// brew install selenium-server-standalone
// brew cask install chromedriver
// go get "github.com/sclevine/agouti"
// go get "github.com/pkg/errors"

var adPage = "http://local.hoge/"

var driver = agouti.ChromeDriver()
var page *agouti.Page

func init() {
	driver.Debug = true

	if err := driver.Start(); err != nil {
		panic(errors.Wrap(err, "Failed to start driver"))
	}

	_page, err := driver.NewPage(agouti.Browser("chrome"))
	if err != nil {
		panic(err)
	}

	page = _page
}

func setCookie() {
	uuid := fmt.Sprintf("clickbot_%d", time.Now().Unix())
	err := page.Navigate("http://hoge.local/")
	if err != nil {
		panic(err)
	}
	time.Sleep(1000 * time.Millisecond)
	err = page.SetCookie(&http.Cookie{
		Name:   "uuid",
		Value:  uuid,
		Path:   "/",
		Domain: ".local",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("Refresh cookie uuid: " + uuid)
}

func main() {
	defer driver.Stop()
	setCookie()

	errcount := 0
	count := 0
	for {
		count++
		if count%5 == 0 {
			setCookie()
		}

		var err error
		err = page.Navigate(adPage)
		if err != nil {
			errcount++
		}

		time.Sleep(1000 * time.Millisecond)

		err = page.FindByXPath("/html/body/*/a[1]").Click()
		if err != nil {
			errcount++
		}

		time.Sleep(3000 * time.Millisecond)
	}
}