org.openqa.selenium.phantomjs.PhantomJSDriver Java Examples

The following examples show how to use org.openqa.selenium.phantomjs.PhantomJSDriver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebUITest.java    From blog with MIT License 6 votes vote down vote up
@BeforeClass
public static void startServer() throws ServletException {
	
	// INIT WEB SERVER (TOMCAT)
	server = new EmbeddedServer(8080, "/20150118-test-selenium");
	server.start();

	// INIT WEB BROWSER (SELENIUM + PHANTOMJS)
	driver = new PhantomJSDriver(
	new DesiredCapabilities(ImmutableMap.of( //
			PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, //
			new PhantomJsDownloader().downloadAndExtract()
					.getAbsolutePath())));
	baseUrl = "http://localhost:8080/20150118-test-selenium";
	driver.manage().timeouts().implicitlyWait(5, SECONDS);
}
 
Example #2
Source File: IndexStep.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Use phantomjs to fetch the web content.
 * @return WebDriver.
 */
protected WebDriver phantomJsDriver() {
    String phantomJsExecPath =  System.getProperty("phantomjsExec");
    if(phantomJsExecPath == null || "".equals(phantomJsExecPath)) {
        phantomJsExecPath = "/usr/local/bin/phantomjs";
    }
    DesiredCapabilities dc = new DesiredCapabilities();
    dc.setJavascriptEnabled(true);
    dc.setCapability(
        PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
        phantomJsExecPath
    );
    return new PhantomJSDriver(dc);
}
 
Example #3
Source File: WebUITest.java    From blog with MIT License 5 votes vote down vote up
@Override
public WebDriver getDefaultDriver() {

	// INIT WEB BROWSER (SELENIUM + PHANTOMJS)
	driver = new PhantomJSDriver(new DesiredCapabilities(ImmutableMap.of( //
			PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, //
			new PhantomJsDownloader().downloadAndExtract()
					.getAbsolutePath())));
	baseUrl = "http://localhost:8080/20150125-test-fluentlenium";
	driver.manage().timeouts().implicitlyWait(5, SECONDS);

	return driver;
}
 
Example #4
Source File: MainIT.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void testExecute()
throws Exception
{
    System.setProperty("phantomjs.binary.path", System.getProperty("phantomjs.binary"));
    WebDriver driver = new PhantomJSDriver();
    
    // And now use this to visit birt report viewer
    driver.get("http://localhost:9999");

    // Check the title of the page
    assertEquals("Eclipse BIRT Home", driver.getTitle());
    
    // Click view exmaple button       
    WebElement element = driver.findElement(By.linkText("View Example"));
    element.click();

    // Wait until page loaded
    (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {

            // Check the title of loaded page
            assertEquals("BIRT Report Viewer", d.getTitle());


            // Check the success message
            assertTrue(d.getPageSource().contains("Congratulations!"));
            return true;
        }
    });

    //Close the browser
    driver.quit();    
}
 
Example #5
Source File: HtmlExporterUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * Release those resource of phantomjs, include shutdown phantom process.
 *
 * @param driver close cannot shutdown, should do it with quit()
 */
public static void release(PhantomJSDriver driver) {
    try {
        if (driver != null) driver.close();
    } finally {
        if (driver != null) driver.quit();
    }
}
 
Example #6
Source File: HtmlExporterUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
     * 初始化配置 PhantomJS Driver.
     *
     * @param url         目标 URL
     * @param addedCookie 添加 cookie
     * @return 初始化过的 PhantomJS Driver
     */
    public static PhantomJSDriver prepare(String url, Cookie addedCookie, Integer width, Integer height) {
        // chrome driver maybe not necessary
        // download from https://sites.google.com/a/chromium.org/chromedriver/downloads
//        System.setProperty("webdriver.chrome.driver",
//                DirUtils.RESOURCES_PATH.concat(
//                        PropUtils.getInstance().getProperty("html.exporter.webdriver.chrome.driver")));

        DesiredCapabilities phantomCaps = DesiredCapabilities.chrome();
        phantomCaps.setJavascriptEnabled(true);
        PropUtils p = PropUtils.getInstance();
        phantomCaps.setCapability("phantomjs.page.settings.userAgent",
                p.getProperty("html.exporter.user.agent"));

        PhantomJSDriver driver = new PhantomJSDriver(phantomCaps);
        driver.manage().timeouts().implicitlyWait(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.implicitly.seconds")), TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.page.load.seconds")), TimeUnit.SECONDS);
        driver.manage().timeouts().setScriptTimeout(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.script.seconds")), TimeUnit.SECONDS);

        if (width == null || height == null) driver.manage().window().maximize();
        else driver.manage().window().setSize(new Dimension(width, height));

        if (addedCookie != null) driver.manage().addCookie(addedCookie);

        driver.get(url);
//        try {
//            // timeout is not work, so fix it by sleeping thread
//            Thread.sleep(Integer.valueOf(PropUtils.getInstance()
//                    .getProperty("html.exporter.driver.timeouts.implicitly.seconds")) * 1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        return driver;
    }
 
Example #7
Source File: HtmlExporter2File.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片文件
 */
@Override
public File convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.FILE);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #8
Source File: HtmlExporter2BASE64.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片 string 字符串
 */
@Override
public String convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.BASE64);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #9
Source File: HtmlExporter2BYTES.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片 byte 数组
 */
@Override
public byte[] convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.BYTES);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #10
Source File: PhantomJsFactory.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param config
 * @return A FirefoxDriver.
 */
@Override
public RemoteWebDriver make(HashMap<String, String> config) {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setJavascriptEnabled(true);
    if (System.getProperty(PHANTOMJS_PATH_PROPERTY) != null) {
        path = System.getProperty(PHANTOMJS_PATH_PROPERTY);
    }
    caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                    path);
    return new PhantomJSDriver(caps);
}
 
Example #11
Source File: PhantomJSDriverConfig.java    From jmeter-plugins-webdriver with Apache License 2.0 5 votes vote down vote up
@Override
public void threadFinished() {
    final PhantomJSDriver phantomJsDriver = removeThreadBrowser();
    if (phantomJsDriver != null) {
        phantomJsDriver.quit();
    }
}
 
Example #12
Source File: LocalWebDriverTest.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 5 votes vote down vote up
@Test
public void testWithHeadlessBrowsers(HtmlUnitDriver htmlUnit,
        PhantomJSDriver phantomjs) {
    htmlUnit.get("https://bonigarcia.github.io/selenium-jupiter/");
    phantomjs.get("https://bonigarcia.github.io/selenium-jupiter/");

    assertTrue(htmlUnit.getTitle().contains("JUnit 5 extension"));
    assertNotNull(phantomjs.getPageSource());
}
 
Example #13
Source File: RealHtmlElementState.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private void highlightElement(
                               boolean disregardConfiguration ) {

    if (webDriver instanceof PhantomJSDriver) {
        // it is headless browser
        return;
    }

    if (disregardConfiguration || UiEngineConfigurator.getInstance().getHighlightElements()) {

        try {
            WebElement webElement = RealHtmlElementLocator.findElement(element);
            String styleAttrValue = webElement.getAttribute("style");

            JavascriptExecutor js = (JavascriptExecutor) webDriver;
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                             webElement,
                             "background-color: #ff9; border: 1px solid yellow; box-shadow: 0px 0px 10px #fa0;"); // to change text use: "color: yellow; text-shadow: 0 0 2px #f00;"
            Thread.sleep(500);
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                             webElement,
                             styleAttrValue);
        } catch (Exception e) {
            // swallow this error as highlighting is not critical
        }
    }
}
 
Example #14
Source File: RealHtmlElement.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Simulate Enter key
 */
@Override
@PublicAtsApi
public void pressEnterKey() {

    new RealHtmlElementState(this).waitToBecomeExisting();

    WebElement element = RealHtmlElementLocator.findElement(this);
    if (webDriver instanceof PhantomJSDriver) {
        element.sendKeys(Keys.ENTER);
    } else {
        element.sendKeys(Keys.RETURN);
    }
}
 
Example #15
Source File: PhatomJsTest.java    From webdrivermanager-examples with Apache License 2.0 4 votes vote down vote up
@Before
public void setupTest() {
    driver = new PhantomJSDriver();
}
 
Example #16
Source File: PerformancePhantomJsTest.java    From webdrivermanager-examples with Apache License 2.0 4 votes vote down vote up
@Before
public void setupTest() {
    for (int i = 0; i < NUMBER_OF_BROWSERS; i++) {
        driverList.add(new PhantomJSDriver());
    }
}
 
Example #17
Source File: PhantomJsBrowser.java    From SeleniumCucumber with GNU General Public License v3.0 4 votes vote down vote up
public WebDriver getPhantomJsDriver(PhantomJSDriverService sev,
		Capabilities cap) {

	return new PhantomJSDriver(sev, cap);
}
 
Example #18
Source File: WebDriverTest.java    From webdrivermanager with Apache License 2.0 4 votes vote down vote up
@Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
    return asList(new Object[][] { { ChromeDriver.class },
            { FirefoxDriver.class }, { PhantomJSDriver.class } });
}
 
Example #19
Source File: PhantomJsTest.java    From webdrivermanager with Apache License 2.0 4 votes vote down vote up
@Before
public void setupTest() {
    driver = new PhantomJSDriver();
}
 
Example #20
Source File: BrowserUtilsTest.java    From jlineup with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldGetPhantomJSDriver() {
    final JobConfig jobConfig = jobConfigBuilder().withBrowser(PHANTOMJS).build();
    assertSetDriverType(jobConfig, PhantomJSDriver.class);
}
 
Example #21
Source File: BrowserDetectionImpl.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
@Override
public boolean isPhantomJS(@NotNull final WebDriver webDriver) {
	checkNotNull(webDriver);
	return webDriver instanceof PhantomJSDriver;
}
 
Example #22
Source File: SeleniumPhantomjsPageLoader.java    From xxl-crawler with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Document load(PageRequest pageRequest) {
    if (!UrlUtil.isUrl(pageRequest.getUrl())) {
        return null;
    }

    // driver init
    DesiredCapabilities dcaps = new DesiredCapabilities();
    dcaps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, !pageRequest.isValidateTLSCertificates());
    dcaps.setCapability(CapabilityType.TAKES_SCREENSHOT, false);
    dcaps.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true);
    dcaps.setJavascriptEnabled(true);
    if (driverPath!=null && driverPath.trim().length()>0) {
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, driverPath);
    }

    if (pageRequest.getProxy() != null) {
        dcaps.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
        dcaps.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
        System.setProperty("http.nonProxyHosts", "localhost");
        dcaps.setCapability(CapabilityType.PROXY, pageRequest.getProxy());
    }

    /*dcaps.setBrowserName(BrowserType.CHROME);
    dcaps.setVersion("70");
    dcaps.setPlatform(Platform.WIN10);*/

    WebDriver webDriver = new PhantomJSDriver(dcaps);

    try {
        // driver run
        webDriver.get(pageRequest.getUrl());

        if (pageRequest.getCookieMap() != null && !pageRequest.getCookieMap().isEmpty()) {
            for (Map.Entry<String, String> item: pageRequest.getCookieMap().entrySet()) {
                webDriver.manage().addCookie(new Cookie(item.getKey(), item.getValue()));
            }
        }

        webDriver.manage().timeouts().implicitlyWait(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);
        webDriver.manage().timeouts().pageLoadTimeout(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);
        webDriver.manage().timeouts().setScriptTimeout(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);

        String pageSource = webDriver.getPageSource();
        if (pageSource != null) {
            Document html = Jsoup.parse(pageSource);
            return html;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (webDriver != null) {
            webDriver.quit();
        }
    }
    return null;
}
 
Example #23
Source File: PhantomjsJupiterTest.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
@Test
public void test(PhantomJSDriver driver) {
    driver.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver.getPageSource(), notNullValue());
}
 
Example #24
Source File: SeleniumExtension.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
public SeleniumExtension() {
    addEntry(handlerMap, "org.openqa.selenium.chrome.ChromeDriver",
            ChromeDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.firefox.FirefoxDriver",
            FirefoxDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.edge.EdgeDriver",
            EdgeDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.opera.OperaDriver",
            OperaDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.safari.SafariDriver",
            SafariDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.remote.RemoteWebDriver",
            RemoteDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.WebDriver",
            RemoteDriverHandler.class);
    addEntry(handlerMap, "io.appium.java_client.AppiumDriver",
            AppiumDriverHandler.class);
    addEntry(handlerMap, "java.util.List", ListDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.phantomjs.PhantomJSDriver",
            OtherDriverHandler.class);
    addEntry(handlerMap, "org.openqa.selenium.ie.InternetExplorerDriver",
            InternetExplorerDriverHandler.class);
    addEntry(handlerMap, "com.codeborne.selenide.SelenideDriver",
            SelenideDriverHandler.class);

    addEntry(templateHandlerMap, "chrome", ChromeDriver.class);
    addEntry(templateHandlerMap, "firefox", FirefoxDriver.class);
    addEntry(templateHandlerMap, "edge", EdgeDriver.class);
    addEntry(templateHandlerMap, "opera", OperaDriver.class);
    addEntry(templateHandlerMap, "safari", SafariDriver.class);
    addEntry(templateHandlerMap, "appium", AppiumDriver.class);
    addEntry(templateHandlerMap, "phantomjs", PhantomJSDriver.class);
    addEntry(templateHandlerMap, "iexplorer", InternetExplorerDriver.class);
    addEntry(templateHandlerMap, "internet explorer",
            InternetExplorerDriver.class);
    addEntry(templateHandlerMap, "chrome-in-docker", RemoteWebDriver.class);
    addEntry(templateHandlerMap, "firefox-in-docker",
            RemoteWebDriver.class);
    addEntry(templateHandlerMap, "opera-in-docker", RemoteWebDriver.class);
    addEntry(templateHandlerMap, "edge-in-docker", RemoteWebDriver.class);
    addEntry(templateHandlerMap, "iexplorer-in-docker",
            RemoteWebDriver.class);
    addEntry(templateHandlerMap, "android", RemoteWebDriver.class);
    addEntry(templateHandlerMap, "selenide", SelenideDriverHandler.class);
}
 
Example #25
Source File: AspectAttributeTest.java    From viritin with Apache License 2.0 4 votes vote down vote up
public AspectAttributeTest() {
    WebDriver webDriver = new PhantomJSDriver();
    startBrowser(webDriver);
}
 
Example #26
Source File: IndexHtmlTest.java    From JGiven with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void createWebDriver() {
    webDriver = new PhantomJSDriver();
}
 
Example #27
Source File: PhantomJSDriverConfig.java    From jmeter-plugins-webdriver with Apache License 2.0 4 votes vote down vote up
@Override
protected PhantomJSDriver createBrowser() {
    return new PhantomJSDriver(createCapabilities());
}