当前位置:首页 > 文章列表 > Golang > Go问答 > 使用Golang和Docker运行Selenium和Chrome

使用Golang和Docker运行Selenium和Chrome

来源:stackoverflow 2024-02-05 22:18:24 0浏览 收藏

今天golang学习网给大家带来了《使用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.3selenium/standalone-chrome:4.9.0 进行了测试。结果是,它适用于 4.8.3,但不适用于 4.9.0。这至少证明 4.9.0 引入了重大更改。

以上就是《使用Golang和Docker运行Selenium和Chrome》的详细内容,更多关于的资料请关注golang学习网公众号!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
如何对返回通道类型的Golang函数进行测试?如何对返回通道类型的Golang函数进行测试?
上一篇
如何对返回通道类型的Golang函数进行测试?
在没有 sqlmock 的情况下如何模拟数据库连接测试
下一篇
在没有 sqlmock 的情况下如何模拟数据库连接测试
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    499次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • PandaWiki开源知识库:AI大模型驱动,智能文档与AI创作、问答、搜索一体化平台
    PandaWiki开源知识库
    PandaWiki是一款AI大模型驱动的开源知识库搭建系统,助您快速构建产品/技术文档、FAQ、博客。提供AI创作、问答、搜索能力,支持富文本编辑、多格式导出,并可轻松集成与多来源内容导入。
    125次使用
  • SEO  AI Mermaid 流程图:自然语言生成,文本驱动可视化创作
    AI Mermaid流程图
    SEO AI Mermaid 流程图工具:基于 Mermaid 语法,AI 辅助,自然语言生成流程图,提升可视化创作效率,适用于开发者、产品经理、教育工作者。
    922次使用
  • 搜获客笔记生成器:小红书医美爆款内容AI创作神器
    搜获客【笔记生成器】
    搜获客笔记生成器,国内首个聚焦小红书医美垂类的AI文案工具。1500万爆款文案库,行业专属算法,助您高效创作合规、引流的医美笔记,提升运营效率,引爆小红书流量!
    943次使用
  • iTerms:一站式法律AI工作台,智能合同审查起草与法律问答专家
    iTerms
    iTerms是一款专业的一站式法律AI工作台,提供AI合同审查、AI合同起草及AI法律问答服务。通过智能问答、深度思考与联网检索,助您高效检索法律法规与司法判例,告别传统模板,实现合同一键起草与在线编辑,大幅提升法律事务处理效率。
    957次使用
  • TokenPony:AI大模型API聚合平台,一站式接入,高效稳定高性价比
    TokenPony
    TokenPony是讯盟科技旗下的AI大模型聚合API平台。通过统一接口接入DeepSeek、Kimi、Qwen等主流模型,支持1024K超长上下文,实现零配置、免部署、极速响应与高性价比的AI应用开发,助力专业用户轻松构建智能服务。
    1025次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码