Selenium 可以在没有 GUI 的情况下在 Ubuntu 上工作吗

Will Selenium work on Ubuntu with no GUI

我在 Amazon AWS 和 Cloud 9 等各种云平台上使用 Codeception。默认情况下它们都没有 GUI。我的问题是,你能在这种类型的系统上 运行 Selenium 吗?或者我需要以某种方式获得 GUI 吗?

Selenium 只是一个库,因此它并不特别关心您是否在配备 GUI 的系统上 运行 它。您可能会问:如果我使用 Selenium 打开浏览器,该浏览器是否可以在没有 GUI 的系统上运行。答案是:视情况而定!

有无头浏览器:也没有 GUI 组件的浏览器。 HtmlUnit is packaged with Selenium. Another popular browser is PhantomJS, which has third-party Selenium bindings library called GhostDriver. Personally I would avoid both of these! HtmlUnit uses a JavaScript engine that none of the current desktop browsers support, and as such the tests are not very reliable. GhostDriver has not been maintained for 2 years, and as such also makes for unreliable results. PahntomJS is definitely an option, as it uses WebKit - the engine that is in Safari and Chrome browsers, but you would have to write your own API.

大多数系统都允许您拥有虚拟 GUI。您提到了 Ubuntu,它是 Debian 的衍生产品。网上有几个教程告诉您如何安装 Xvfb,其中大部分都不完整或有误。在 Debian 上,你安装一个像这样的无头浏览器:

  1. 安装 Xvfb:apt-get install xvfb
  2. 安装浏览器。假设您使用的是 Debian 服务器,您将无法使用 apt-get 安装类似 Firefox 的东西,因为存储库不存在。相反 Google 类似 "Firefox off-line install" 的东西,或者你想使用的任何浏览器,然后在你的服务器上使用 wget 来获取包。
  3. 将包解压到 /usr/local/lib 之类的地方,然后从 /usr/local/bin 创建一个软 link 到启动浏览器的二进制文件。
  4. 现在尝试无头启动浏览器。例如,对于 Firefox,您可以尝试:xvfb-run firefox。这可能会产生一些错误,您必须修复这些错误。就我而言,我缺少可以使用 apt-get 安装的库 libdbus-glib-1-2
  5. 此时您需要在 运行 Selenium 测试之前启动 Xvfb。大多数 CI 服务器都有 Xvfb 插件,或者您可以从命令行执行此操作:Xvfb :99 &。有关更多信息,请参阅 docs