tl;dr
如何安装所有组件以在 docker 容器中运行 Selenium?
Question
我从这张图片开始:
FROM microsoft/aspnetcore-build:2 AS builder
WORKDIR /source
COPY . .
RUN dotnet restore
RUN dotnet build
ENTRYPOINT ["dotnet", "run"]
我怎样才能启动并使用无头 Chrome 驱动程序:
ChromeOptions options = new ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--disable-gpu");
var driverPath = Path.GetFullPath(Path.Combine(environment.ContentRootPath, "bin/Debug/netcoreapp2.0"));
return new ChromeDriver(driverPath, options, TimeSpan.FromSeconds(60));
在 docker 容器内?
我尝试过什么
安装 Chrome 驱动程序
The chromedriver
是通过Selenium.WebDriver.ChromeDriver
NuGet 包。
安装 Chrome
在我安装了 Google Chrome 的 Mac OS X 上,当前设置运行得很好。
我尝试添加这些行:
RUN apt-get update && apt-get -y install libglib2.0-dev libxi6 libnss3-dev
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
RUN apt-get update && apt-get -y install google-chrome-stable
以上安装了此版本的 Chrome:
google-chrome-stable:
Installed: 64.0.3282.119-1
Candidate: 64.0.3282.119-1
Version table:
*** 64.0.3282.119-1 500
500 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages
100 /var/lib/dpkg/status
与 Chrome 驱动程序的版本兼容。
这是因为尝试解决通过尝试使用 docker 容器运行 Selenium 时出现的每个错误。
如果我运行这个设置,我会得到:
启动 ChromeDriver 2.35.528139
(47ead77cb35ad2a9a83248b292151462a66cd881) 端口 57889 仅限本地
允许连接。发送请求时发生错误。
无法连接到
运行容器时。
在容器中调试
如果我手动进入容器并尝试手动运行 chrome 驱动程序,我会得到:
在端口 9515 上启动 ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)
仅允许本地连接。
和跑步curl -i http://localhost:9515/status
I get:
HTTP/1.1 200 OK
Content-Length:136
Content-Type:application/json; charset=utf-8
Connection:close
{"sessionId":"","status":0,"value":{"build":{"version":"alpha"},"os":{"arch":"x86_64","name":"Linux","version":"4.9.60-linuxkit-aufs"}}}
所以看来驱动程序工作得很好。
如果我通过以下方式运行 chrome headlessgoogle-chrome-stable --headless --disable-cpu --no-sandbox
I get:
[0125/210641.877388:WARNING:discardable_shared_memory_manager.cc(178)] Less than 64MB of free space in temporary directory for shared memory files: 63
[0125/210641.902689:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[0125/210641.902756:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[0125/210642.031088:ERROR:instance.cc(49)] Unable to locate service manifest for metrics
[0125/210642.031119:ERROR:service_manager.cc(890)] Failed to resolve service name: metrics
[0125/210642.032934:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
第一个警告可以通过设置 docker 卷来解决/dev/shm:/dev/shm
或通过设置-shm-size
到大的东西(高于 64MB)。
其余的错误,如果谷歌的话,会导致我从 Google Chrome 存储库中获得许多错误报告。