开发手册 欢迎您!
软件开发者资料库

Java 通过Selenium WebDriver 和命令行方式使用PhantomJS方法及示例代码

本文主要介绍Java中调用PhantomJS的两种方法及示例代码,分别是使用Selenium WebDriver调用PhantomJS,使用命行方式调用PhantomJS。

1、PhantomJS下载

下载地址https://phantomjs.org/download.html

2、WebDriver下载

下载地址https://www.seleniumhq.org/download/

3、使用Selenium WebDriver 调用PhantomJS

DesiredCapabilities caps = new DesiredCapabilities();caps.setJavascriptEnabled(true);                caps.setCapability("takesScreenshot", true);  caps.setCapability(                        PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,                        "path\\phantomjs.exe"//phantomjs.exe所在路径                    );WebDriver driver = new  PhantomJSDriver(caps);

import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.phantomjs.PhantomJSDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;public class Selenium2Example  {    public static void main(String[] args) {//创建Firefox驱动程序的一个新实例//注意,代码的其余部分依赖于接口,//不是实现。        System.setProperty("phantomjs.binary.path", System.getProperty("user.dir")+"/phantomjs");        WebDriver driver = new PhantomJSDriver();        //现在用这个访问谷歌        driver.get("http://www.google.com");        // 同样的事情也可以这样做        // driver.navigate().to("http://www.google.com");        // 根据文本输入元素的名称查找它        WebElement element = driver.findElement(By.name("q"));        // 输入要搜索的内容        element.sendKeys("Cheese!");        // 现在提交表单。WebDriver将从元素中为我们找到表单        element.submit();        // 检查页面的标题        System.out.println("Page title is: " + driver.getTitle());       //谷歌的搜索是用JavaScript动态呈现的。       //等待页面加载,超时10秒        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {            public Boolean apply(WebDriver d) {                return d.getTitle().toLowerCase().startsWith("cheese!");            }        });        // 应该看到: "cheese! - Google Search"        System.out.println("Page title is: " + driver.getTitle());        //关闭浏览器        driver.quit();    }}

4、使用命令行直接调用PhantomJS

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * @Description:根据网页地址转换成图片 * @Author: admin * @CreateDate: 2018年6月22日 */public class PhantomTools {    private static String tempPath = "D:/temp/img";// 图片保存目录    private static String BLANK = " ";    // 下面内容可以在配置文件中配置    private static String binPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe";// 插件引入地址    private static String jsPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/examples/rasterize.js";// js引入地址    // 执行cmd命令    public static String cmd(String imgagePath, String url) {        return binPath + BLANK + jsPath + BLANK + url + BLANK + imgagePath;    }    //关闭命令    public static void close(Process process, BufferedReader bufferedReader) throws IOException {        if (bufferedReader != null) {            bufferedReader.close();        }        if (process != null) {            process.destroy();            process = null;        }    }    /**     * @param userId      * @param url     * @throws IOException      */    public static void printUrlScreen2jpg(String url) throws IOException{        String imgagePath = tempPath+"/"+System.currentTimeMillis()+".png";//图片路径        //Java中使用Runtime和Process类运行外部程序        Process process = Runtime.getRuntime().exec(cmd(imgagePath,url));        InputStream inputStream = process.getInputStream();        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));        String tmp = "";        while ((tmp = reader.readLine()) != null) {            close(process,reader);        }        System.out.println("success");    }    public static void main(String[] args) throws IOException {        String url = "https://www.baidu.com/";        PhantomTools.printUrlScreen2jpg(url);    }}