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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Python および WebDriver 拡張機能: Web ページでのマウス ホイール操作のシミュレート はじめに: Web インタラクション デザインの継続的な開発に伴い、自動テストにおけるユーザー操作のシミュレートがますます重要になってきています。一部の Web ページでは、マウス ホイールの使用が一般的な操作の 1 つになっています。ただし、Python を使用して自動テスト スクリプトを作成する開発者にとって、WebDriver でマウス ホイール操作をシミュレートする方法が課題になる場合があります。この記事ではPythonとWebDrivを使った方法を紹介します。

Python と WebDriver を使用して Web ページのスクリーンショットを作成し、PDF ファイルとして保存する 概要: Web 開発およびテスト中に、分析、記録、レポート作成のために Web ページのスクリーンショットを作成することが必要になることがよくあります。この記事では、Python と WebDriver を使用して Web ページのスクリーンショットを撮り、そのスクリーンショットを PDF ファイルとして保存して簡単に共有したりアーカイブしたりする方法を紹介します。 1. SeleniumWebDriver をインストールして構成します。 Python をインストールします。 Python 公式 Web サイト (https:

Python と WebDriver を使用して、Web ページに認証コードを自動的に入力します。インターネットの発展に伴い、セキュリティの向上と自動攻撃の防止を目的として、ユーザー登録やログインなどの操作に認証コードの仕組みを導入する Web サイトが増えています。ただし、検証コードを手動で入力するのは面倒なだけでなく、ユーザー エクスペリエンスが複雑になります。では、認証コードを自動的に入力する方法はあるのでしょうか?答えは「はい」です。この記事では、PythonとWebDriverを使ってWebページに認証コードを自動入力する方法を紹介します。まず、私は

Python と WebDriver を使用して Web ページの自動更新を実装する はじめに: 毎日の Web ブラウジングでは、リアルタイム データの監視、動的ページの自動更新など、Web ページの頻繁な更新が必要なシナリオによく遭遇します。 Web ページを手動で更新すると多くの時間とエネルギーが無駄になります。そのため、Python と WebDriver を使用して Web ページを自動的に更新する機能を実装し、作業効率を向上させることができます。 1. インストールと構成環境 開始する前に、対応する環境をインストールして構成する必要があります。 Pythonをインストールする

Python と WebDriver を使用して Web ページ上のフォーム データを自動的に入力することは、ソフトウェア開発プロセスの重要な部分であり、Web フォームの自動入力もその 1 つです。開発者にとって、フォームに手動で入力するのは面倒でエラーが発生しやすいプロセスです。 Python と WebDriver を使用して自動テスト プロセス中にテーブル データを自動的に入力すると、手動での作業の重複が減り、テストの効率が向上します。この記事ではPythonでSeleniumを使う方法を紹介します。

Python および WebDriver 拡張機能: Web ページでの右クリックのマウス クリックをシミュレートする Python と WebDriver を使用して自動 Web ページ テストを行う場合、多くの場合、クリック、ドラッグ、右クリック メニュー操作などのユーザーのマウス動作をシミュレートする必要があります。 WebDriver は、クリック、ドラッグ アンド ドロップなどのいくつかの基本的なマウス アクション関数を提供しますが、マウスの右クリックをシミュレートする関数を直接提供するわけではありません。この記事ではPythonとWebDの使い方を紹介します。

Python と WebDriver の拡張機能を使用して、Web ページのドラッグ アンド ドロップ操作を自動化します。実際の Web アプリケーションでは、ドラッグ アンド ドロップ (ドラッグ アンド ドロップ) は一般的な対話型操作であり、ユーザー エクスペリエンスと利便性を向上させることができます。 Web ページのドラッグ アンド ドロップ操作を自動化することは、テスターにとって重要かつ一般的なタスクです。この記事では、Python と WebDriver 拡張機能を使用して、Web ページ上のドラッグ アンド ドロップ操作を自動化する方法を紹介します。 1. 準備 始める前に、Pyt をインストールする必要があります

Python と WebDriver を使用してフォーム自動入力機能を実装する 日常の Web サイト閲覧では、フォームに入力する必要がある場面に遭遇することがよくあります。同じまたは類似のフォームに頻繁に入力する必要がある場合、手動で入力するのは面倒で時間がかかります。幸いなことに、Python と WebDriver を使用すると、フォームに自動入力する機能を実現し、作業効率を向上させることができます。まず、Selenium ライブラリをインストールする必要があります。 Selenium は、シミュレーションを実行できる自動テスト ツールです。
