`
ljl_xyf
  • 浏览: 617989 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

C#和java调用phantomjs采集ajax加载生成的网页

 
阅读更多
     日前有采集需求,当我把所有的对应页面的链接都拿到手,准备开始根据链接去采集(写爬虫爬取)对应的终端页的时候,发觉用程序获取到的数据根本没有对应 的内容,可是我的浏览器看到的内容明明是有的,于是浏览器查看源代码也发觉没有,此时想起该网页应该是ajax加载的。不知道ajax的小朋友可以去学下 web开发啦。
    采集ajax生成的内容手段不外乎两种。一种是通过http观察加载页面时候的请求,然后我们模仿该请求去得到对应的内容,第二种则是模仿浏览器行为去渲 染这个页面得到内容。我在这里决定采用第二种方式,之前一直玩webkit,不过一直要加载页面太浪费资源了,此时了解到有一个好玩的玩意 phantomjs,这是个可以用命令行来操作webkit的玩意,然后也可以直接在里面用js的api去操作页面(当然,我这边比较简单就懒得用了)。
    下载完phantomjs之后直接解压就可以使用,然后在path目录加入phantomjs的路径(以便直接在命令行就可以执行phantomjs命令)。
    接下来要完成个代码,一个是用phantomjs去获取页面(采用js编写行为),一个是采用java去调用phantomjs来达到获取内容的作用,接下来直接贴代码。
codes.js
/codes.js   
system = require('system')   
address = system.args[1];//获得命令行第二个参数 接下来会用到   
//console.log('Loading a web page');   
var page = require('webpage').create();   
var url = address;   
//console.log(url);   
page.open(url, function (status) {   
    //Page is loaded!   
    if (status !== 'success') {   
        console.log('Unable to post!');   
    } else {   
        //console.log(page.content);   
        //var title = page.evaluate(function() {   
        //  return document.title;//示范下如何使用页面的jsapi去操作页面的  www.oicqzone.com 
        //  });   
        //console.log(title);   
        //console.log(encodeURIComponent(page.content));    
        console.log(page.content);   
    }      
    phantom.exit();   
});    
 
上述的js代码估计应该没几个看不懂的。。。
接下来贴java代码!
import org.apache.commons.io.IOUtils;   
   
import java.io.*;   
   
/**  
 * Created with IntelliJ IDEA.  
 * User: lsz  
 * Date: 14-4-22  
 * Time: 下午1:17  
 * utils for http  
 */   
public class HttpUtils {   
    public static String getAjaxCotnent(String url) throws IOException {   
        Runtime rt = Runtime.getRuntime();   
        Process p = rt.exec("phantomjs.exe c:/phantomjs/codes.js "+url);//这里我的codes.js是保存在c盘下面的phantomjs目录   
        InputStream is = p.getInputStream();   
        BufferedReader br = new BufferedReader(new InputStreamReader(is));   
        StringBuffer sbf = new StringBuffer();   
        String tmp = "";   
        while((tmp = br.readLine())!=null){   
            sbf.append(tmp);   
        }   
        //System.out.println(sbf.toString());   
        return sbf.toString();   
    }   
   
    public static void main(String[] args) throws IOException {   
        getAjaxCotnent("http://www.plusweb.cn");   
    }   
}   
 C#实现代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;

namespace phantomjs
{
    class Program
    {
        static void Main(string[] args)
        {

            // String str = getAjaxCotnent("http://www.plusweb.cn");//测试使用
            new Program().listHttp();
           
        }

        public static String getAjaxCotnent(String url)
        {

            ProcessStartInfo start = new ProcessStartInfo(Environment.CurrentDirectory + "//phantomjs//phantomjs.exe");//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到
            //如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe
            start.Arguments = "phantomjs//code.js" + " " + url;//设置命令参数
            StringBuilder sb = new StringBuilder();
            start.CreateNoWindow = false;//不显示dos命令行窗口
            start.RedirectStandardOutput = true;//
            start.RedirectStandardInput = true;//
            start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
            Process p = Process.Start(start);
            
            string encoding = p.StandardOutput.CurrentEncoding.ToString();
            StreamReader reader = p.StandardOutput;//截取输出流
            string line = reader.ReadLine();//每次读取一行
            sb.AppendLine(line);
            while (!reader.EndOfStream)
            {
                
                line = reader.ReadLine();
                sb.AppendLine(line);
            }
            p.WaitForExit();//等待程序执行完退出进程
            p.Close();//关闭进程 
            reader.Close();//关闭流
            string strRet =  System.Web.HttpUtility.UrlDecode(sb.ToString());
           return strRet;
        }



        private void listHttp()
        {



            using (HttpListener listerner = new HttpListener())
            {
                string urllister = System.Configuration.ConfigurationSettings.AppSettings["listurl"];
                listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                //listerner.Prefixes.Add(urllister);               
                listerner.Prefixes.Add("http://localhost/web/");
                listerner.Start();
                Console.WriteLine("WebServer Start Successed.......");
                while (true)
                {
                    //等待请求连接
                    //没有请求则GetContext处于阻塞状态
                    HttpListenerContext ctx = listerner.GetContext();
                    ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
                    string url = ctx.Request.QueryString["url"];
                    //使用Writer输出http响应代码
                    using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                    {
                        writer.WriteLine(getAjaxCotnent(url));
                        writer.Close();
                        ctx.Response.Close();
                    }

                }
                listerner.Stop();
            }
        }
    }

}
 启动器c#程序访问以下地址:
http://localhost/web/?url=http%3A%2F%2Fwww.plusweb.cn
进行测试
 
其实原理很简单,就是通过进程间通信用java调用phantomjs这个组件去请求渲染页面,不过这种做法因为每次都要重新启动phantomjs进 程,所以比较慢,还有另外一种直接用phantomjs加载页面后,把内容post给我们自定义的一个http后端接收数据,会更快一点。
phantomjs下载地址:
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics