当前位置:首页 > 文章列表 > 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基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • SEO标题魔匠AI:高质量学术写作平台,毕业论文生成与优化专家
    魔匠AI
    SEO摘要魔匠AI专注于高质量AI学术写作,已稳定运行6年。提供无限改稿、选题优化、大纲生成、多语言支持、真实参考文献、数据图表生成、查重降重等全流程服务,确保论文质量与隐私安全。适用于专科、本科、硕士学生及研究者,满足多语言学术需求。
    25次使用
  • PPTFake答辩PPT生成器:一键生成高效专业的答辩PPT
    PPTFake答辩PPT生成器
    PPTFake答辩PPT生成器,专为答辩准备设计,极致高效生成PPT与自述稿。智能解析内容,提供多样模板,数据可视化,贴心配套服务,灵活自主编辑,降低制作门槛,适用于各类答辩场景。
    39次使用
  • SEO标题Lovart AI:全球首个设计领域AI智能体,实现全链路设计自动化
    Lovart
    SEO摘要探索Lovart AI,这款专注于设计领域的AI智能体,通过多模态模型集成和智能任务拆解,实现全链路设计自动化。无论是品牌全案设计、广告与视频制作,还是文创内容创作,Lovart AI都能满足您的需求,提升设计效率,降低成本。
    53次使用
  • 美图AI抠图:行业领先的智能图像处理技术,3秒出图,精准无误
    美图AI抠图
    美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
    49次使用
  • SEO标题PetGPT:智能桌面宠物程序,结合AI对话的个性化陪伴工具
    PetGPT
    SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
    50次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码