Golang Docker Selenium Chrome

golang docker selenium chrome

Golang Docker Selenium Chrome是一种强大的组合,为开发人员提供了便捷且高效的工具链。Golang是一种高性能的编程语言,具有简洁的语法和强大的并发性能。Docker是一种容器化技术,可以将应用程序与其依赖项打包成一个独立的运行环境。Selenium是一个自动化测试工具,可以模拟用户在浏览器中的操作。而Chrome是一款流行的Web浏览器。通过结合使用这些工具,开发人员可以更方便地进行Web应用程序的开发和测试。在本文中,我们将深入探讨如何使用Golang Docker Selenium Chrome来加速开发过程,并分享一些实用技巧和最佳实践。

问题内容

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

package mainimport (    "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", 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", 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", 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", err.error())    }    passwordfield, err := wd.findelement(selenium.byid, "dfg")    if err != nil {        fmt.printf("falha ao encontrar o campo de senha: %s", err.error())    }    err = passwordfield.sendkeys("dlfknvkxjcn ")    if err != nil {        fmt.printf("falha ao preencher o campo de senha: %s", 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", err.error())    }    err = loginbutton.click()    if err != nil {        fmt.printf("falha ao clicar no botão de login: %s", 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", err)    }    err = access.click()    if err != nil {        fmt.printf("falha ao clicar no botão de acesso: %s", 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:

立即学习“go语言免费学习笔记(深入)”;

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: 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","exception.stacktrace": "org.openqa.selenium.NoSuchSessionException: 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: unknownat org.openqa.selenium.grid.sessionmap.local.LocalSessionMap.get(LocalSessionMap.java:137)at org.openqa.selenium.grid.router.HandleSession.lambda$loadSessionId$4(HandleSession.java:172)at io.opentelemetry.context.Context.lambda$wrap$2(Context.java:224)at org.openqa.selenium.grid.router.HandleSession.execute(HandleSession.java:125)at org.openqa.selenium.remote.http.Route$PredicatedRoute.handle(Route.java:384)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.grid.router.Router.execute(Router.java:87)at org.openqa.selenium.grid.web.EnsureSpecCompliantResponseHeaders.lambda$apply$0(EnsureSpecCompliantResponseHeaders.java:34)at org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$NestedRoute.handle(Route.java:271)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.http.Route$CombinedRoute.handle(Route.java:347)at org.openqa.selenium.remote.http.Route.execute(Route.java:69)at org.openqa.selenium.remote.AddWebDriverSpecHeaders.lambda$apply$0(AddWebDriverSpecHeaders.java:35)at org.openqa.selenium.remote.ErrorFilter.lambda$apply$0(ErrorFilter.java:44)at org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)at org.openqa.selenium.remote.ErrorFilter.lambda$apply$0(ErrorFilter.java:44)at org.openqa.selenium.remote.http.Filter$1.execute(Filter.java:63)at org.openqa.selenium.netty.server.SeleniumHandler.lambda$channelRead0$0(SeleniumHandler.java:44)at java.baseu002fjava.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)at java.baseu002fjava.util.concurrent.FutureTask.run(FutureTask.java:264)at java.baseu002fjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)at java.baseu002fjava.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)at java.baseu002fjava.lang.Thread.run(Thread.java:829)","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": "u002fsessionu002fu002furl","http.user_agent": "Go-http-clientu002f1.1","session.id": ""}}

登录后复制

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

解决方法

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

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

登录后复制

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

警告 [seleniumspanexporter$1.lambda$export$1] – org.openqa.selenium.sessionnotcreatedexception:无法启动新会话。与驱动程序服务创建会话时出错。停止驱动程序服务:无法启动新会话。握手响应与任何支持的协议不匹配。响应负载:{“sessionid”:”4ef27eb4d2fbb1ebfe5cf2fb51df731b”,”status”:33,”value”:{“message”:”会话未创建:缺少或无效的功能(驱动程序信息:chromedriver =114.0.5735.90 (386bc09e8f4f2e025eddae123f36f6263096ae49-refs/branch-heads/5735@{#1052}),platform=linux 5.19.0-43-通用 x86_64)”}}

这可能是由删除 json wire 协议支持引入的重大更改引起的,在 selenium 4.9.0 中提供。

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

以上就是Golang Docker Selenium Chrome的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2484078.html

(0)
上一篇 2025年3月4日 21:27:34
下一篇 2025年2月18日 23:42:57

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • C++框架中的测试策略:创建健壮且可维护的应用程序

    问题: c++++ 框架中的测试策略包括哪些步骤?答案:单元测试集成测试功能测试端到端测试 C++ 框架中的测试策略:构建健壮且可维护的应用程序 在现代软件开发中,测试已成为确保应用程序质量和可靠性的至关重要的方面。C++ 框架提供了一套工…

    2025年3月3日
    200
  • Golang 框架中常见的测试和调试技巧有哪些?

    测试和调试技巧:测试技巧:单元测试:测试单个函数,使用 testing 包。集成测试:模拟客户端请求,测试整体功能,使用 httptest 包。端到端测试:模拟用户交互,使用 webdriver 或真实客户端。调试技巧:debugger 关…

    2025年3月1日
    200
  • golang框架自动化测试的Selenium指南

    Golang 框架 Selenium 自动化测试指南 简介Selenium 是一种用于自动化 Web 应用程序测试的流行开源工具。它与各种编程语言兼容,包括 Go。本文将指导您在 Golang 框架中使用 Selenium 进行自动化测试。…

    2025年2月28日
    200
  • golang自动化测试的最佳实践是什么?

    golang 自动化测试最佳实践:单测:细粒度、快速、断言明确集成测试:隔离、覆盖范围、模拟依赖关系端到端测试:真实环境、自动化、受控 Golang 自动化测试的最佳实践 引言 在现代软件开发中,自动化测试已成为一种至关重要的实践,可提高软…

    2025年2月28日
    200
  • 如何在 Golang 中测试 UI 接口?

    在 golang 中测试 ui 接口需要使用自动化测试框架,如 selenium。安装 selenium 后,可执行以下步骤进行测试:初始化 webdriver访问目标网站输入查询提交查询等待结果加载检查结果页面是否有匹配的结果打印结果标题…

    2025年2月28日
    200
  • Python 测试框架:打造高质量软件的秘密武器

    单元测试:细粒度代码验证 单元测试框架允许开发者测试代码的最小组成部分(单元),确保每个函数或方法都按预期工作。流行的单元测试框架包括: unittest: python 内置的单元测试框架,提供广泛的基本功能。pytest: 一个灵活和可…

    2025年2月26日
    200
  • python自动化脚本怎么写

    编写 Python 自动化脚本的步骤包括:确定自动化任务。安装 Python 和相关库。导入必要的 Python 模块。编写脚本,包括导入、类/函数定义和脚本正文。调试和测试脚本以确保正确运行。 Python 自动化脚本编写指南 自动化脚本…

    2025年2月26日
    200
  • python爬虫url怎么获得

    利用 Python 爬虫获取 URL 的方法:使用 requests 库使用 BeautifulSoup 库使用 urllib 库使用 Selenium 库 利用Python爬虫获取URL 在Python中获取URL有几种方法,具体取决于上…

    2025年2月25日
    200
  • python爬虫怎么获取ajax

    有三种方法可以获取 AJAX 数据:解析响应文本:使用 requests 库发送请求并解析响应文本。使用 Selenium:自动化浏览器并执行 AJAX 请求。使用 Node.js 代理:在爬虫和网站之间转发请求并拦截 AJAX 请求。 如…

    2025年2月25日
    200
  • python爬虫怎么编写

    编写Python爬虫涉及以下步骤:选择库(BeautifulSoup、Requests、Selenium);编写爬虫(定义目标URL、发送请求、解析响应、提取数据);处理分页(检查下一页链接、提取下一页URL、构建下一页请求);处理Java…

    2025年2月25日
    400

发表回复

登录后才能评论