docker - Golang Docker Selenium Chrome

标签 docker go selenium-webdriver

我在 golang 中有一个 api,它尝试连接到在 docker 镜像中运行的 selenium 服务器:

package main

import (
    "fmt"
    "time"

    "github.com/tebeka/selenium"
    "github.com/tebeka/selenium/chrome"
)

func main() {
    // Configuração webdriver (simulador)
    caps := selenium.Capabilities{
        "browserName": "chrome", "browserVersion": "114.0", "se:noVncPort": 7900, "se:vncEnabled": true,
    }

    chromeCaps := chrome.Capabilities{
        Args: []string{
            "--headless",
        },
    }
    caps.AddChrome(chromeCaps)

    // Iniciando o servidor, conectado ao eu webdriver que esta rodando
    wd, err := selenium.NewRemote(caps, "http://localhost:4444/wd/hub")
    if err != nil {
        fmt.Printf("Falha ao iniciar o servidor Selenium: %s\n", err.Error())
        return
    }
    defer wd.Quit()
    time.Sleep(10 * time.Second)

    // inicia a pagina inicial kk
    err = wd.Get("https://www.csonline.com.br/")
    if err != nil {
        fmt.Printf("Falha ao abrir a página de login: %s\n", err.Error())
        return
    }

    time.Sleep(10 * time.Second)

    // Selecionar o elemento por ID
    usernameField, err := wd.FindElement(selenium.ByID, "dfgd")
    if err != nil {
        fmt.Printf("Falha ao encontrar o campo de usuário: %s\n", err)
        return
    }

    //populando os campos, ai é só repetir os passos
    err = usernameField.SendKeys("dfglkdf)
    if err != nil {
        fmt.Printf("Falha ao preencher o campo de usuário: %s\n", err.Error())
    }

    passwordField, err := wd.FindElement(selenium.ByID, "dfg")
    if err != nil {
        fmt.Printf("Falha ao encontrar o campo de senha: %s\n", err.Error())
    }

    err = passwordField.SendKeys("dlfknvkxjcn ")
    if err != nil {
        fmt.Printf("Falha ao preencher o campo de senha: %s\n", err.Error())
    }

    // Envia o formulário de login
    loginButton, err := wd.FindElement(selenium.ByCSSSelector, "#next")
    if err != nil {
        fmt.Printf("Falha ao encontrar o botão de login: %s\n", err.Error())
    }
    err = loginButton.Click()
    if err != nil {
        fmt.Printf("Falha ao clicar no botão de login: %s\n", err.Error())
    }
    fmt.Println("Sucess")

    //aguarda um tempo para realizar login
    time.Sleep(10 * time.Second)

    Access, err := wd.FindElement(selenium.ByID, "btnSelectLogin")
    if err != nil {
        fmt.Printf("Falha ao encontrar o botão de acesso: %s\n", err)

    }
    err = Access.Click()
    if err != nil {
        fmt.Printf("Falha ao clicar no botão de acesso: %s\n", err)

    }
    fmt.Println("Sucess")

    localStorageScript := `return localStorage.getItem("cs.token");`

    // Execute o script no contexto do navegador
    localStorageData, err := wd.ExecuteScript(localStorageScript, nil)
    if err != nil {
        fmt.Println("Falha ao obter dados do LocalStorage:", err)

    }

    // Imprima os dados do LocalStorage
    fmt.Println("Bearer", localStorageData)

}

我在docker中安装了selenium,如下所示:

docker pull selenium/standalone-chrome

我运行此命令在 docker 中启动 selenium:

docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome

运行命令时 go run main.go 我在 go 终端中收到此错误:

invalid session id: Unable to execute request for an existing session: Unable to find session with ID: 
Build info: version: '4.10.0', revision: 'c14d967899'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.16.3-microsoft-standard-WSL2', java.version: '11.0.19'
Driver info: driver.version: unknown

在 docker 中的 selenium 日志中我得到:

WARN [SeleniumSpanExporter$1.lambda$export$3] - {"traceId": "171e16c9402c8f85639418c7b458f388","eventTime": 1687963769139610379,"eventName": "exception","attributes": {"exception.message": "Unable to execute request for an existing session: Unable to find session with ID: \nBuild info: version: '4.10.0', revision: 'c14d967899'\nSystem info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.16.3-microsoft-standard-WSL2', java.version: '11.0.19'\nDriver info: driver.version: unknown","exception.stacktrace": "org.openqa.selenium.NoSuchSessionException: Unable to find session with ID: \nBuild info: version: '4.10.0', revision: 'c14d967899'\nSystem info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.10.16.3-microsoft-standard-WSL2', java.version: '11.0.19'\nDriver info: driver.version: unknown\n\tat org.openqa.selenium.grid.sessionmap.local.LocalSessionMap.get(LocalSessionMap.java:137)\n\tat org.openqa.selenium.grid.router.HandleSession.lambda$loadSessionId$4(HandleSession.java:172)\n\tat io.opentelemetry.context.Context.lambda$wrap$2(Context.java:224)\n\tat org.openqa.selenium.grid.router.HandleSession.execute(HandleSession.java:125)\n\tat org.openqa.selenium.remote.http.Route$PredicatedRoute.handle(Route.java:384)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.grid.router.Router.execute(Router.java:87)\n\tat org.openqa.selenium.grid.web.EnsureSpecCompliantResponseHeaders.lambda$apply$0(EnsureSpecCompliantResponseHeaders.java:34)\n\tat org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$NestedRoute.handle(Route.java:271)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)\n\tat org.openqa.selenium.remote.http.Route.execute(Route.java:69)\n\tat org.openqa.selenium.remote.AddWebDriverSpecHeaders.lambda$apply$0(AddWebDriverSpecHeaders.java:35)\n\tat org.openqa.selenium.remote.ErrorFilter.lambda$apply$0(ErrorFilter.java:44)\n\tat org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)\n\tat org.openqa.selenium.remote.ErrorFilter.lambda$apply$0(ErrorFilter.java:44)\n\tat org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)\n\tat org.openqa.selenium.netty.server.SeleniumHandler.lambda$channelRead0$0(SeleniumHandler.java:44)\n\tat java.base\u002fjava.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)\n\tat java.base\u002fjava.util.concurrent.FutureTask.run(FutureTask.java:264)\n\tat java.base\u002fjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\n\tat java.base\u002fjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\n\tat java.base\u002fjava.lang.Thread.run(Thread.java:829)\n","exception.type": "org.openqa.selenium.NoSuchSessionException","http.flavor": 1,"http.handler_class": "org.openqa.selenium.grid.router.HandleSession","http.host": "localhost:4444","http.method": "POST","http.request_content_length": "38","http.scheme": "HTTP","http.target": "\u002fsession\u002f\u002furl","http.user_agent": "Go-http-client\u002f1.1","session.id": ""}}

为什么会发生这种情况?有人可以提供帮助吗?

最佳答案

要使您的演示与 selenium/standalone-chrome:latest 一起使用(目前为 selenium/standalone-chrome:4.10.0),您需要将 W3C 设置为 true:

chromeCaps := chrome.Capabilities{
    Args: []string{
        "--headless",
    },
    W3C: true,
}

如果你仔细查看容器的日志,你应该会看到类似这样的内容:

WARN [SeleniumSpanExporter$1.lambda$export$1] - org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Error while creating session with the driver service. Stopping driver service: Could not start a new session. Handshake response does not match any supported protocol. Response payload: {"sessionId":"4ef27eb4d2fbb1ebfe5cf2fb51df731b","status":33,"value":{"message":"session not created: Missing or invalid capabilities\n (Driver info: chromedriver=114.0.5735.90 (386bc09e8f4f2e025eddae123f36f6263096ae49-refs/branch-heads/5735@{#1052}),platform=Linux 5.19.0-43-generic x86_64)"}}

这可能是由 Remove Json Wire Protocol support 引入的重大更改引起的,它是在 Selenium 4.9.0 中提供的。

我从演示中删除了 "browserVersion": "114.0",然后针对 selenium/standalone-chrome:4.8.3selenium/standalone 进行了测试-chrome:4.9.0。结果是它适用于 4.8.3,但不适用于 4.9.0。这至少证明 4.9.0 引入了重大更改。

关于docker - Golang Docker Selenium Chrome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76574419/

相关文章:

docker - ERRO[0043] 无法调用 gRPC : unable to upgrade to h2c, 收到 501

golangci-lint - 想要 "really"忽略 go 文件,而不是简单地分析它并抑制警告 - 我目前的忽略方法会占用内存并且速度很慢

python - Selenium Python 无法定位元素

Python - Selenium 下一页

python - Selenium 无法打开指定的 URL 并显示数据 :,

postgresql - Fedora:应用程序容器无法建立与数据库容器的连接

docker - 作业完成后自动关闭 AWS 实例

docker - docker缺少var/lib/docker文件夹

select - break 语句是否从 switch/select 中断?

go - Hyperledger 链码外部服务调用