목차
问题内容
解决方法
백엔드 개발 Golang Golang Docker 셀레늄 크롬

Golang Docker 셀레늄 크롬

Feb 10, 2024 pm 01:30 PM
webdriver

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.3selenium/standalone-chrome:4.9.0 进行了测试。结果是,它适用于 4.8.3,但不适用于 4.9.0。这至少证明 4.9.0 引入了重大更改。

위 내용은 Golang Docker 셀레늄 크롬의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python 및 WebDriver를 사용하여 웹 페이지를 캡처하고 PDF 파일로 저장 Python 및 WebDriver를 사용하여 웹 페이지를 캡처하고 PDF 파일로 저장 Jul 08, 2023 pm 10:55 PM

Python 및 WebDriver를 사용하여 웹 페이지 스크린샷을 캡처하고 PDF 파일로 저장 요약: 웹 개발 및 테스트 중에 분석, 기록 및 보고를 위해 웹 페이지 스크린샷을 캡처해야 하는 경우가 많습니다. 이 기사에서는 Python 및 WebDriver를 사용하여 웹 페이지의 스크린샷을 찍고 스크린샷을 PDF 파일로 저장하여 쉽게 공유하고 보관하는 방법을 소개합니다. 1. SeleniumWebDriver 설치 및 구성: Python 설치: Python 공식 웹사이트(https:

Python 및 WebDriver 확장: 웹 페이지에서 마우스 휠 작업 시뮬레이션 Python 및 WebDriver 확장: 웹 페이지에서 마우스 휠 작업 시뮬레이션 Jul 09, 2023 pm 11:55 PM

Python 및 WebDriver 확장: 웹 페이지에서 마우스 휠 작업 시뮬레이션 소개: 웹 상호 작용 디자인의 지속적인 개발로 인해 자동화된 테스트에서 사용자 작업 시뮬레이션이 점점 더 중요해졌습니다. 일부 웹페이지에서는 마우스 휠을 사용하는 것이 일반적인 작업 중 하나가 되었습니다. 그러나 Python을 사용하여 자동화된 테스트 스크립트를 작성하는 개발자의 경우 WebDriver에서 마우스 휠 작업을 시뮬레이션하는 방법이 어려울 수 있습니다. 이번 글에서는 Python과 WebDriv를 이용한 방법을 소개하겠습니다.

Python 및 WebDriver를 사용하여 웹 페이지의 인증 코드를 자동으로 입력하세요. Python 및 WebDriver를 사용하여 웹 페이지의 인증 코드를 자동으로 입력하세요. Jul 07, 2023 am 10:19 AM

Python 및 WebDriver를 사용하여 웹 페이지에 자동으로 인증 코드를 입력하세요. 인터넷이 발전하면서 점점 더 많은 웹사이트에서 보안을 강화하고 자동화된 공격을 방지하기 위해 사용자 등록, 로그인 및 기타 작업에 인증 코드 메커니즘을 도입했습니다. 그러나 인증 코드를 수동으로 입력하는 것은 번거로울 뿐만 아니라 사용자 경험의 복잡성을 증가시킵니다. 그렇다면 인증번호를 자동으로 입력할 수 있는 방법은 없을까요? 대답은 '예'입니다. 이 글에서는 Python과 WebDriver를 사용하여 웹 페이지에 인증 코드를 자동으로 입력하는 방법을 소개합니다. 첫째로, 나는

Python 및 WebDriver를 사용하여 웹 페이지 자동 새로 고침 Python 및 WebDriver를 사용하여 웹 페이지 자동 새로 고침 Jul 08, 2023 pm 01:46 PM

Python 및 WebDriver를 사용하여 자동 웹 페이지 새로 고침 구현 소개: 일상적인 웹 탐색에서 실시간 데이터 모니터링, 동적 페이지 자동 새로 고침 등과 같이 빈번한 웹 페이지 새로 고침이 필요한 시나리오를 자주 접하게 됩니다. 웹 페이지를 수동으로 새로 고치는 것은 많은 시간과 에너지를 낭비하므로 Python과 WebDriver를 사용하여 웹 페이지를 자동으로 새로 고치는 기능을 구현하고 작업 효율성을 향상시킬 수 있습니다. 1. 설치 및 환경 구성 시작하기 전에 해당 환경을 설치하고 구성해야 합니다. 파이썬 설치

Python 및 WebDriver 확장: 웹 페이지에서 마우스 오른쪽 버튼 클릭 시뮬레이션 Python 및 WebDriver 확장: 웹 페이지에서 마우스 오른쪽 버튼 클릭 시뮬레이션 Jul 07, 2023 am 11:22 AM

Python 및 WebDriver 확장: 웹 페이지에서 마우스 오른쪽 버튼 클릭 시뮬레이션 자동화된 웹 페이지 테스트를 위해 Python 및 WebDriver를 사용할 때 클릭, 드래그 및 마우스 오른쪽 버튼 클릭 메뉴 작업과 같은 사용자 마우스 동작을 시뮬레이션해야 하는 경우가 많습니다. WebDriver는 클릭, 드래그 앤 드롭 등과 같은 몇 가지 기본적인 마우스 동작 기능을 제공하지만 마우스 오른쪽 버튼 클릭을 시뮬레이션하는 기능을 직접 제공하지는 않습니다. 이 기사에서는 Python과 WebD를 사용하는 방법을 소개합니다.

Python 및 WebDriver를 사용하여 웹 페이지의 테이블 데이터 자동 채우기 Python 및 WebDriver를 사용하여 웹 페이지의 테이블 데이터 자동 채우기 Jul 07, 2023 pm 08:37 PM

Python 및 WebDriver를 사용하여 웹 페이지의 양식 데이터를 자동으로 채우는 것은 소프트웨어 개발 프로세스의 중요한 부분 중 하나는 웹 양식의 자동 채우기입니다. 개발자에게 양식을 수동으로 작성하는 것은 지루하고 오류가 발생하기 쉬운 프로세스입니다. 자동 테스트 프로세스 중에 Python 및 WebDriver를 사용하여 테이블 데이터를 자동으로 채우면 수동 작업 중복을 줄이고 테스트 효율성을 높일 수 있습니다. 이번 글에서는 Python에서 Selenium을 사용하는 방법을 소개하겠습니다.

Python 및 WebDriver 확장을 사용하여 웹 페이지에서 끌어서 놓기 작업 자동화 Python 및 WebDriver 확장을 사용하여 웹 페이지에서 끌어서 놓기 작업 자동화 Jul 10, 2023 pm 07:09 PM

Python 및 WebDriver 확장을 사용하여 웹 페이지의 드래그 앤 드롭 작업을 자동화합니다. 실제 웹 애플리케이션에서 드래그 앤 드롭(Drag and Drop)은 사용자 경험과 편의성을 향상시킬 수 있는 일반적인 대화형 작업입니다. 웹 페이지의 끌어서 놓기 작업을 자동화하는 것은 테스터에게 중요하고 일반적인 작업입니다. 이 기사에서는 Python 및 WebDriver 확장을 사용하여 웹 페이지에서 끌어서 놓기 작업을 자동화하는 방법을 소개합니다. 1. 준비 시작하기 전에 Pyt를 설치해야 합니다.

Python 및 WebDriver를 사용하여 양식 자동 채우기 기능 구현 Python 및 WebDriver를 사용하여 양식 자동 채우기 기능 구현 Jul 07, 2023 am 10:25 AM

Python 및 WebDriver를 사용하여 양식 자동 채우기 기능 구현 일상적인 웹 사이트 탐색에서 양식을 작성해야 하는 상황에 자주 직면합니다. 동일하거나 유사한 양식을 자주 작성해야 하는 경우 수동으로 작성하는 것은 지루하고 시간이 많이 걸립니다. 다행히 Python과 WebDriver를 사용하면 자동으로 양식을 채우는 기능을 실현하고 작업 효율성을 높일 수 있습니다. 먼저 Selenium 라이브러리를 설치해야 합니다. Selenium은 시뮬레이션할 수 있는 자동화된 테스트 도구입니다.

See all articles