JAVA Selenium PHONCOMJS 获取js动态生成完整网页

首先需要在maven的pom.xml中包含以下依赖

1 <dependency>
2    <groupId>com.github.detro</groupId>
3    <artifactId>phantomjsdriver</artifactId>
4    <version>1.2.0</version>
5 </dependency>

然后从官网 http://phantomjs.org/ 下载 phantomjs

编译安装,因为我是linux(ubuntu 12.04)下的,所以执行

./configure 

make

make install

安装好之后就可以在项目里面调了,注意如果使用maven的话请先update project.

下面是所有源代码:

package com.axsoft.webcounter.base.common;

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class DynamicJSWebUtils {
    
    private static final String PHONCOMJS_PATH = "/usr/local/phantomjs/bin/phantomjs";  //注意这里的路径哦。要设置成自己的
    private static final String CAPABILITY_DEFAULT = "DYNAMIC_WEB_PARSE";
    
    public PhantomJSDriver getPhantomJSDriver(String capability,String toolPath){
        
        System.setProperty("phantomjs.binary.path", null == toolPath || "".equals(toolPath) ? PHONCOMJS_PATH : toolPath);
        // set phantomjs exe path
        
        DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
        desiredCapabilities.setCapability(null == capability || "".equals(capability) ? CAPABILITY_DEFAULT : capability,false);
        desiredCapabilities.setJavascriptEnabled(true);
        return new PhantomJSDriver(desiredCapabilities);
    }
    
    public String getDynamicJSWebContent(String url,String capability,String toolPath)
    {
        PhantomJSDriver driver = getPhantomJSDriver(capability,toolPath);
        driver.get(url);
        String rsp = driver.getPageSource();
        driver.close();
        driver.quit();
        return rsp;
    }
    
    public String getDynamicJSWebContent(String url){
        return getDynamicJSWebContent(url,null,null);
    }
}

 

posted @ 2015-12-01 13:30  kutasms  阅读(896)  评论(0)    收藏  举报