从Java进程运行Selenium

时间:2008-11-26 15:32:39

标签: selenium java

如何从Java进程运行Selenium进程(线程),这样我就不必手动启动Selenium了?

2 个答案:

答案 0 :(得分:9)

服务器:

import org.openqa.selenium.server.SeleniumServer;
public class SeleniumServerControl {
  private static final SeleniumServerControl instance = new SeleniumServerControl();
  public static SeleniumServerControl getInstance() {
    return instance;
  }
  private SeleniumServer server = null;
  protected SeleniumServerControl() {
  }
  public void startSeleniumServer() {
    if (server == null) {
      try {
        server = new SeleniumServer(SeleniumServer.DEFAULT_PORT);
        System.out.println(" selenium server " + server.toString());
      } catch (Exception e) {
        System.err.println("Could not create Selenium Server because of: "
            + e.getMessage());
        e.printStackTrace();
      }
    }
    try {
      server.start();
    } catch (Exception e) {
      System.err.println("Could not start Selenium Server because of: "
          + e.getMessage());
      e.printStackTrace();
    }
  }
  public void stopSeleniumServer() {
    if (server != null) {
      try {
        server.stop();
        server = null;
      } catch (Exception e) {
        System.err.println("Could not stop Selenium Server because of: "
            + e.getMessage());
        e.printStackTrace();
      }
    }
  }
}

客户:

browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com");
browser.start();

答案 1 :(得分:3)

您还可以使用其他一些设置:

    RemoteControlConfiguration settings = new RemoteControlConfiguration();
    File f = new File("/home/user/.mozilla/firefox/default");
    settings.setFirefoxProfileTemplate(f);
    settings.setReuseBrowserSessions(true);
    settings.setSingleWindow(true);
    if (this.ServerWorks == false)
    {
        try
        {
            server = new SeleniumServer(settings);
            server.start();
            this.ServerWorks = true;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }