Golang Docker Selenium Chrome
Golang Docker Selenium Chrome是一种强大的组合,为开发人员提供了便捷且高效的工具链。Golang是一种高性能的编程语言,具有简洁的语法和强大的并发性能。Docker是一种容器化技术,可以将应用程序与其依赖项打包成一个独立的运行环境。Selenium是一个自动化测试工具,可以模拟用户在浏览器中的操作。而Chrome是一款流行的Web浏览器。通过结合使用这些工具,开发人员可以更方便地进行Web应用程序的开发和测试。在本文中,我们将深入探讨如何使用Golang Docker Selenium Chrome来加速开发过程,并分享一些实用技巧和最佳实践。
问题内容
我在 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, }
如果你仔细查看容器的日志,你应该会看到类似这样的内容:
警告 [seleniumspanexporter$1.lambda$export$1] - org.openqa.selenium.sessionnotcreatedexception:无法启动新会话。与驱动程序服务创建会话时出错。停止驱动程序服务:无法启动新会话。握手响应与任何支持的协议不匹配。响应负载:{"sessionid":"4ef27eb4d2fbb1ebfe5cf2fb51df731b","status":33,"value":{"message":"会话未创建:缺少或无效的功能\n(驱动程序信息: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的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Python和WebDriver扩展:在网页中模拟鼠标滚轮操作引言:随着网页交互设计的不断发展,模拟用户操作在自动化测试中变得越来越重要。在一些网页上,鼠标滚轮的使用已经成为了常见的操作之一。然而,对于使用Python编写自动化测试脚本的开发人员来说,如何在WebDriver中模拟鼠标滚轮操作可能会成为一个挑战。本文将介绍一种使用Python和WebDriv

使用Python和WebDriver实现网页截图并保存为PDF文件摘要:在Web开发和测试过程中,经常需要对网页进行截图以便进行分析、记录和报告。本文将介绍如何使用Python和WebDriver来实现网页截图,并将截图保存为PDF文件,以方便分享和存档。一、安装与配置SeleniumWebDriver:安装Python:访问Python官网(https:

使用Python和WebDriver实现网页自动填写验证码随着网络的发展,越来越多的网站在用户注册、登录等操作中引入了验证码机制,以提高安全性和防止自动化攻击。然而,手动输入验证码不仅麻烦,还增加了用户体验的复杂度。那么,有没有一种方法能够自动填写验证码呢?答案是肯定的。本文将介绍如何使用Python和WebDriver实现网页自动填写验证码的方法。首先,我

使用Python和WebDriver实现网页自动刷新引言:在日常的网页浏览中,我们常常会遇到需要频繁刷新网页的场景,比如监控实时数据、自动刷新动态页面等。手动刷新网页会浪费大量的时间和精力,因此我们可以使用Python和WebDriver来实现自动刷新网页的功能,提高我们的工作效率。一、安装和配置环境在开始之前,我们需要安装和配置相应的环境。安装Python

使用Python和WebDriver实现网页自动填充表格数据自动化测试是软件开发过程中重要的一环,其中之一是网页表单的自动填充。对于开发人员来说,手动填写表单是一个枯燥且容易出错的过程。而使用Python和WebDriver,在自动测试过程中实现自动填充表格数据,能够减少人工重复劳动,提高测试效率。在这篇文章中,我将介绍如何使用Python的Selenium

Python和WebDriver扩展:在网页中模拟鼠标右键点击在使用Python和WebDriver进行网页自动化测试时,我们经常需要模拟用户的鼠标行为,例如点击、拖拽和右键菜单等操作。WebDriver会提供一些基本的鼠标行动函数,如click、drag_and_drop等,但是却没有直接提供模拟鼠标右键点击的函数。本文将介绍如何使用Python和WebD

利用Python和WebDriver扩展自动化处理网页的拖放操作在实际的Web应用中,拖放(DragandDrop)是一个常见的交互操作,它可以增强用户的体验和便利性。对于测试人员而言,自动化处理网页的拖放操作是一项重要且常见的任务。本文将介绍如何利用Python和WebDriver扩展自动化处理网页的拖放操作。一、准备工作在开始之前,我们需要安装Pyt

使用Python和WebDriver实现表单自动填写功能在日常的网站浏览中,我们经常会遇到需要填写表单的情况。当我们需要频繁填写相同或类似的表单时,手动填写显得很繁琐而且耗时。所幸的是,我们可以借助Python和WebDriver来实现自动填写表单的功能,提高我们的工作效率。首先,我们需要安装selenium库。Selenium是一个自动化测试工具,可以模拟
