1. 项目地址:
    https://github.com/tebeka/selenium
  2. 用法:
    1. 下载 chromedriver:
      https://sites.google.com/a/chromium.org/chromedriver/
    2. 将 chromedriver 可执行文件放到 path下(略):
    3. 代码:
      package main
      import (
      "fmt"
      "os"
      "strings"
      "time"
      "github.com/tebeka/selenium"
      )
      func main() {
      const (
       seleniumPath    = "/usr/local/bin/chromedriver"
       port            = 8080
      )
      opts := []selenium.ServiceOption{
       //selenium.StartFrameBuffer(),           // Start an X frame buffer for the browser to run in.
       selenium.Output(os.Stderr),            // Output debug information to STDERR.
      }
      selenium.SetDebug(true)
      service, err := selenium.NewChromeDriverService(seleniumPath, port, opts...)
      if err != nil {
       panic(err) // panic is used only as an example and is not otherwise recommended.
      }
      defer service.Stop()
      caps := selenium.Capabilities{"browserName": "chrome"}
      wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
      if err != nil {
       panic(err)
      }
      defer wd.Quit()
      if err := wd.Get("http://play.golang.org/?simple=1"); err != nil {
       panic(err)
      }
      elem, err := wd.FindElement(selenium.ByCSSSelector, "#code")
      if err != nil {
       panic(err)
      }
      if err := elem.Clear(); err != nil {
       panic(err)
      }
      err = elem.SendKeys(`
       package main
       import "fmt"
       func main() {
           fmt.Println("Hello WebDriver!\n")
       }
      `)
      if err != nil {
       panic(err)
      }
      btn, err := wd.FindElement(selenium.ByCSSSelector, "#run")
      if err != nil {
       panic(err)
      }
      if err := btn.Click(); err != nil {
       panic(err)
      }
      outputDiv, err := wd.FindElement(selenium.ByCSSSelector, "#output")
      if err != nil {
       panic(err)
      }
      var output string
      for {
       output, err = outputDiv.Text()
       if err != nil {
           panic(err)
       }
       if output != "Waiting for remote server..." {
           break
       }
       time.Sleep(time.Millisecond * 100)
      }
      fmt.Printf("%s", strings.Replace(output, "\n\n", "\n", -1))
      }
文档更新时间: 2020-11-22 20:37   作者:lee