Golang Selenium包 - 连接到selenium服务器和无头镀铬

时间:2017-05-16 23:09:10

标签: google-chrome selenium docker go

我正在使用Go selenium软件包https://godoc.org/github.com/tebeka/selenium

我在localhost:4444上的docker容器中运行无头chrome + selenium-server

服务器似乎很好,因为我可以通过http://localhost:4444/wd/hub/static/resource/hub.html

访问Web控制台

但我正试图获得#34; Hello world"使用现有docker容器的示例。

这是selenium驱动程序的GoDocs页面中的示例:

// Run some code on play.golang.org and display the result
package main

import (
    "fmt"
    "time"

    "github.com/tebeka/selenium"
)

var code = `
package main
import "fmt"

func main() {
    fmt.Println("Hello WebDriver!\n")
}
`

// Errors are ignored for brevity.

func main() {
    // Connect to the selenium server
    caps := selenium.Capabilities{"browserName": "firefox"}
    wd, err := selenium.NewRemote(caps, "http://127.0.0.1:4444")
    if err != nil {
        fmt.Println(err)
    }
    defer wd.Quit()

    // Get simple playground interface
    wd.Get("http://play.golang.org/?simple=1")

    // Enter code in textarea
    elem, _ := wd.FindElement(selenium.ByCSSSelector, "#code")
    elem.Clear()
    elem.SendKeys(code)

    // Click the run button
    btn, _ := wd.FindElement(selenium.ByCSSSelector, "#run")
    btn.Click()

    // Get the result
    div, _ := wd.FindElement(selenium.ByCSSSelector, "#output")

    output := ""
    // Wait for run to finish
    for {
        output, _ = div.Text()
        if output != "Waiting for remote server..." {
            break
        }
        time.Sleep(time.Millisecond * 100)
    }

    fmt.Printf("Got: %s\n", output)
}

我尝试将"browserName"更改为"chrome"但我收到此错误:

panic: got content type "text/html", expected "application/json"

goroutine 1 [running]:
main.main()
    /home/user01/Code/golang_src/golang_exercises/33_selenium/selenium.go:28 +0x457
exit status 2

我无法在GoDoc selenium文档中找到有关Chrome浏览器以及如何通过selenium-server连接它的任何内容。

我很感激任何关于这里可能出错的提示。

更新

似乎删除了URL地址并将其留空已修复了连接问题:

wd, err := selenium.NewRemote(caps, "")

那就是说,我仍然对这个例子有疑问。主要是它似乎连接到Go Playground网站,获得正确的元素,但是当发送输入elem.SendKeys(code)时,它没有正确发送它并且文本框是空的。导致Playground输出错误:

Got: can't load package: package main: 
tmp/sandbox573608783/main.go:1:1: expected 'package', found 'EOF'

Program exited.

3 个答案:

答案 0 :(得分:0)

经过一些调试后我发现问题是由于我的Docker容器里面没有X服务器。

当selenium包试图发送输入时,它会生成此错误消息:

unknown error: unknown error: an X display is required for keycode conversions, consider using Xvfb
  (Session info: headless chrome=60.0.3095.5)
  (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 4.4.0-77-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 40 milliseconds
Build info: version: '3.3.1', revision: '5234b32', time: '2017-03-10 09:04:52 -0800'
System info: host: 'e3bf5382c62d', ip: '171.14.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-77-generic', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5), userDataDir=/tmp/.org.chromium.Chromium.mFhqlU}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=60.0.3095.5, platform=LINUX, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: 681f9de5f91baeaaa3100cf297767a2d

我还没有在Docker容器中安装X服务器,但我确信它会修复通过selenium向无头chrome实例发送输入时发生的错误。

答案 1 :(得分:0)

我也在Docker中使用selenium,它可以运行:

wd, err := selenium.NewRemote(caps, "http://127.0.0.1:4444/wd/hub")

答案 2 :(得分:0)

尝试以无头模式运行它:

caps := selenium.Capabilities{"browserName": "chrome"}

chromeCaps := chrome.Capabilities{
    Path:  "",
    Args: []string{
        "--headless", // <<<
        "--no-sandbox",
        "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7",
    },
}
caps.AddChrome(chromeCaps)

wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d", port))