JAVA 爬虫获取js动态生成的网页数据

问题:
有些网页数据是由js动态生成的,一般我们抓包可以看出真正的数据实体是由哪一个异步请求获取到的,但是获取数据的请求链接也可能由其他js产生,这个时候我们希望直接拿到js加载后的最终网页数据。

解决方法:
phantomjs
1.下载phantomjs,[官网]:http://phantomjs.org/
2.我们是windows平台,解压,会在bin目录下看到exe可执行文件,有它就够啦。
3.写一个parser.js:

system = require('system')  
address = system.args[1];
var page = require('webpage').create();  
var url = address;  

page.settings.resourceTimeout = 1000*10; // 10 seconds
page.onResourceTimeout = function(e) {
    console.log(page.content);      
    phantom.exit(1);
};

page.open(url, function (status) {  
    //Page is loaded!  
    if (status !== 'success') {  
        console.log('Unable to post!');  
    } else {  
        console.log(page.content);
    }
    phantom.exit(); 
  });

4.java调用

Runtime rt = Runtime.getRuntime();
        Process process = null;
        try {
            process = rt.exec("C:/phantomjs.exe C:/parser.js " +url);
            InputStream in = process.getInputStream();
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(reader);
            StringBuffer sbf = new StringBuffer();
            String tmp = "";
            while ((tmp = br.readLine()) != null) {
                sbf.append(tmp);
            }
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

猜你喜欢

转载自blog.csdn.net/zeroctu/article/details/53818185