配置 Selenium WebDriver

本教程展示了如何创建一个简单的 Selenium WebDriver 应用程序,该应用程序被配置为使用 JxBrowser 访问在桌面 Java 应用程序中加载的网页。

本教程只适用于 Windows 操作系统。

前提条件

为完成本教程,我们需要:

  • Git.
  • Java 8或更高版本。
  • 一个有效的 JxBrowser 许可证。它可以是评估版或商业版。关于许可证的更多信息,请参见许可证指南。
  • 为 Selenium 下载 ChromeDriver。由于JxBrowser是基于Chromium engine的,我们不能使用其他web驱动程序(例如,Firefox WebDriver)。在本教程中使用的是ChromeDriver 88.0.4324.96。

获取代码

要查看本教程中创建的完整应用程序,请查看我们的示例集合:

$ git clone https://github.com/TeamDev-IP/JxBrowser-Examples
$ cd JxBrowser-Examples/tutorials/selenium

JxBrowser应用程序

创建应用程序

创建一个简单的 JxBrowser 应用程序。

添加许可证

要继续,请将许可证密钥放入应用程序中。

配置 Chromium Engine

当 Selenium 启动我们的应用程序时,ChromeDriver 会将--remote-debugging-port=<port> 参数传递给命令行参数。

在我们的应用程序中,我们首先从命令行参数中获取 --remote-debugging-port 参数:

private static Optional<Integer> remoteDebuggingPortFromCommandLine(String[] args) {
    if (args.length > 0) {
        for (String arg : args) {
            if (arg.startsWith(REMOTE_DEBUGGING_PORT_ARG)) {
                String port = arg.substring(REMOTE_DEBUGGING_PORT_ARG.length());
                return Optional.of(Integer.parseInt(port));
            }
        }
    }
    return Optional.empty();
}

然后将其转发到 JxBrowser 启动的 Chromium 引擎:

// Create a builder for EngineOptions.
EngineOptions.Builder builder = EngineOptions.newBuilder(HARDWARE_ACCELERATED);

// Configure Engine with the remote debugging port obtained from the command line args.
remoteDebuggingPortFromCommandLine(args).ifPresent(builder::remoteDebuggingPort);

现在我们可以创建一个 Browser 实例并加载一个网页,Selenium WebDriver 将检测到该网页并通过 ChromeDriver 对它进行处理。

import static com.teamdev.jxbrowser.engine.RenderingMode.HARDWARE_ACCELERATED;

import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.engine.EngineOptions;
import com.teamdev.jxbrowser.view.swing.BrowserView;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Optional;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

/**
 * This example demonstrates how to create a simple Swing application with a web page loaded in
 * BrowserView, and connect JxBrowser's Chromium engine with Selenium via the remote debugging port
 * obtained from the command line.
 */
public final class TargetApp {

    private static final String REMOTE_DEBUGGING_PORT_ARG = "--remote-debugging-port=";

    public static void main(String[] args) {
        // Set your JxBrowser license key.
        System.setProperty("jxbrowser.license.key", "your_license_key");

        // Create a builder for EngineOptions.
        EngineOptions.Builder builder = EngineOptions.newBuilder(HARDWARE_ACCELERATED);

        // Configure Engine with the remote debugging port obtained from the command line args.
        remoteDebuggingPortFromCommandLine(args).ifPresent(builder::remoteDebuggingPort);

        // Creating Chromium engine.
        Engine engine = Engine.newInstance(builder.build());
        Browser browser = engine.newBrowser();

        SwingUtilities.invokeLater(() -> {
            // Creating Swing component for rendering web content
            // loaded in the given Browser instance.
            BrowserView view = BrowserView.newInstance(browser);

            // Creating and displaying Swing app frame.
            JFrame frame = new JFrame();
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    engine.close();
                }
            });
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.add(view, BorderLayout.CENTER);
            frame.setSize(800, 700);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            browser.navigation().loadUrl("https://google.com");
        });
    }

    private static Optional<Integer> remoteDebuggingPortFromCommandLine(String[] args) {
        if (args.length > 0) {
            for (String arg : args) {
                if (arg.startsWith(REMOTE_DEBUGGING_PORT_ARG)) {
                    String port = arg.substring(REMOTE_DEBUGGING_PORT_ARG.length());
                    return Optional.of(Integer.parseInt(port));
                }
            }
        }
        return Optional.empty();
    }
}

查看完整的应用程序

创建可执行文件

要创建我们程序的可执行文件,可以使用 launch4j Gradle 插件或以您方便的任何方式手动创建它。

Selenium应用程序

安装 Selenium 依赖项

创建一个单独的项目并安装依赖性,以便用ChromeDriver运行Selenium测试。

配置 Selenium WebDriver

要告诉 Selenium 在哪里可以找到应用程序,请提供应用程序的可执行文件的绝对/相对路径,如下所示:

ChromeOptions options = new ChromeOptions();

// Set a path to your JxBrowser application executable.
options.setBinary(
        new File("tutorials/selenium/target-app/build/executable/TargetApp.exe"));

然后指定远程调试端口,以便与基于 JxBrowser 的应用程序进行通信:

// Set a port to communicate on.
options.addArguments("--remote-debugging-port=9222");

该端口不应被其他应用程序使用。 在本教程中,我们使用 9222,但您可以随意使用任何其他可用端口。

完整的应用程序运行:

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 * An application that configures Selenium WebDriver (ChromeDriver) to run on the JxBrowser-based
 * application binaries and get access to HTML content loaded in JxBrowser.
 */
public final class SeleniumLauncher {

    public static void main(String[] args) {
        // Set a path to the ChromeDriver executable.
        System.setProperty("webdriver.chrome.driver",
                "tutorials/selenium/launcher/src/main/resources/chromedriver.exe");

        ChromeOptions options = new ChromeOptions();

        // Set a path to your JxBrowser application executable.
        options.setBinary(
                new File("tutorials/selenium/target-app/build/executable/TargetApp.exe"));
        // Set a port to communicate on.
        options.addArguments("--remote-debugging-port=9222");

        WebDriver driver = new ChromeDriver(options);

        // Now you can use WebDriver.
        System.out.printf("Current URL: %s\n", driver.getCurrentUrl());

        driver.quit();
    }
}

查看完整的应用程序

运行 Selenium

运行 Selenium,如果一切配置正确,您将看到一个带有 Google 网页的 Java 窗口:

Application

在控制台中,您应该看到以下输出:

Current URL: https://www.google.com/

这意味着 Selenium WebDriver 成功运行了我们的应用程序,与 JxBrowser 的 Chromium引擎建立了连接,并访问加载的网页以打印其 URL。

首次启动 Selenium 时,基于 JxBrowser 的应用程序本身可能会成功启动,但您可能会看到以下 ChromeDriver 错误消息:The process started from chrome location path\to\application.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed. 这表明ChromeDriver没有设法找到正在运行的应用程序。我们还不知道如何解决这个问题,但如果您不关闭已启动的应用程序并再次运行Selenium,驱动程序将会检测到正在运行的应用程序二进制文件并成功启动。

总结

在本教程中,我们:

  1. 创建两个应用程序:我们集成 JxBrowser 以显示网页的应用程序,以及连接到第一个应用程序并访问 JxBrowser 中加载的网页的带有 Selenium ChromeDriver 的应用程序。
  2. 展示如何使带有 JxBrowser 的应用程序对 Selenium “可见”。
  3. 在基于 JxBrowser 的应用程序二进制文件上运行 Selenium 应用程序以演示其工作原理。
Go Top