我在Golang中有一个API,它try 连接到在docker映像中运行的Selify服务器:

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中启动Selify:

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

运行命令时,请运行main.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日志(log)中,我得到了:

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,
}

如果你仔细查看容器的日志(log),你应该会看到如下所示:

WARN[Seleniumspan Exporter$1.lambda$EXPORT$1]-org.openqa.selenium.SessionNotCreatedException:无法启动新会话.创建与驱动程序服务的会话时出错.正在停止驱动程序服务:无法启动新会话.握手响应与任何支持的协议都不匹配.响应负载:{"sessionId":"4ef27eb4d2fbb1ebfe5cf2fb51df731b","Status":33,"Value":{"Message":"session not created: Missing or invalid capabilities\n(驱动程序信息:chromeDriver=114.0.5735.90(386bc09e8f4f2e025eddae123f36f6263096ae49-refs/branch-heads/5735@{#1052}),Platform=linux 5.19.0-43-Generic x86_64)"}}

这可能是由Selenium 4.9.0年出厂的Remove Json Wire Protocol support引入的突破性变化造成的.

我从您的演示中删除了"browserVersion": "114.0",然后将其与selenium/standalone-chrome:4.8.3selenium/standalone-chrome:4.9.0进行了测试.结果是,它可以在4.8.3上运行,但不能在4.9.0上运行.这至少证明了4.9.0引入了一个突破性的变化.

Go相关问答推荐

Go 1.22 http mux:在同一路径上提供一个手柄和一个FS

在保留额外参数的同时解封YAML

切换选项卡时,Goland IDE中的光标自动转移

../golang/pkg/mod/github.com/wmentor/lemmas@v0.0.6/processor.go:72:9:未定义:令牌.进程

创建使用逗号而不是加号分隔OU的CSR

mockgen不创建模拟

可以';t从主机连接到ScyllaDB容器

如何模拟go的Elastic search SDK?

将这两个函数合二为一的惯用方法

按位移计算结果中的差异

Go test "-run -" 标志执行测试更快

Go 中的 YAML 自定义标签

为什么docall在singleflight中使用go panic?

如何将 base64 编码的公钥转换为 crypto.PublicKey 或 ecdsa.PublicKey

使用 Go 解组 SOAP 消息

emersion/go-imap - imap.FetchRFC822:无效内存地址或零指针取消引用

CORS grpc 网关 GoLang

使用 `didip/tollbooth` 限制每小时最大请求数

vs 代码调试 go 测试不通过标志

使用 LoadLibraryA(path_to_dll) 加载 DLL 会将文件描述符 0、1 和 2 的继承句柄标志 (HANDLE_FLAG_INHERIT) 从 1 更改为 0