日前有采集需求,当我把所有的对应页面的链接都拿到手,准备开始根据链接去采集(写爬虫爬取)对应的终端页的时候,发觉用程序获取到的数据根本没有对应 的内容,可是我的浏览器看到的内容明明是有的,于是浏览器查看源代码也发觉没有,此时想起该网页应该是ajax加载的。不知道ajax的小朋友可以去学下 web开发啦。
采集ajax生成的内容手段不外乎两种。一种是通过http观察加载页面时候的请求,然后我们模仿该请求去得到对应的内容,第二种则是模仿浏览器行为去渲 染这个页面得到内容。我在这里决定采用第二种方式,之前一直玩webkit,不过一直要加载页面太浪费资源了,此时了解到有一个好玩的玩意 phantomjs,这是个可以用命令行来操作webkit的玩意,然后也可以直接在里面用js的api去操作页面(当然,我这边比较简单就懒得用了)。
下载完phantomjs之后直接解压就可以使用,然后在path目录加入phantomjs的路径(以便直接在命令行就可以执行phantomjs命令)。
接下来要完成个代码,一个是用phantomjs去获取页面(采用js编写行为),一个是采用java去调用phantomjs来达到获取内容的作用,接下来直接贴代码。
codes.js
http://localhost/web/?url=http%3A%2F%2Fwww.plusweb.cn
进行测试
/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下载地址:
相关推荐
首先,PhantomJS是一款无头浏览器,即它没有图形用户界面,但能够像普通浏览器一样加载和执行JavaScript,这对于网页抓取非常有用。而Selenium WebDriver则是一个自动化测试工具,它可以控制各种浏览器并模拟用户...
在本项目实践中,我们探索了如何使用C#.NET框架结合PhantomJS和Selenium构建一个高级的网络爬虫程序,该程序能够处理JavaScript渲染的网页并执行JavaScript代码,从而更全面地获取网络数据。以下是对这个项目的详细...
可执行Javascript代码、触发各类事件、操纵页面Dom结构。 爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集...然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
基于CasperJS和PhantomJS,可以自动渲染网页、动态解析js,支持ajax和各类前端交互。 代码基于phantomjs爬虫小记 by wils0n ,在tuicool上也有这篇文章http://www.tuicool.com/articles/JbEfIvV , 原作者的代码在...
总之,这个.NET C# Demo提供了一种实现HighCharts图表导出图片的方法,通过工具类和控制器协同工作,能够在后端生成图片并返回给前端。这个过程涉及到JavaScript与服务器端的交互、无头浏览器的使用以及HTTP响应的...
6. Support for AJAX 和 JavaScript:由于现代Web应用大量使用AJAX和JavaScript,Selenium 2.40.0能够处理页面异步加载的情况,确保测试的准确性。 7. Exception Handling:在编写测试脚本时,Selenium 提供了丰富...
4. **动态加载**:对于使用 AJAX 动态加载的网站,可以使用 Selenium 自动化工具,模拟真实用户行为。 **网络爬虫的其他语言** 虽然 Python 是爬虫领域最流行的语言,但其他语言也有其独特之处: 1. **JavaScript...
虽然题目中提到的是".net 截图修改",但在JSP环境下,我们可以使用.NET组件(如Awesomium或CEFSharp)通过C#创建一个Web服务,该服务接收前端上传的图片数据,利用.NET的屏幕捕获功能生成更高质量的全屏截图。...
这个过程可能使用HTML2Canvas或者 PhantomJS 等技术,它们可以将HTML和CSS转换为图像。 4. **ASP.NET MVC或Web Forms**: 根据项目选择,这个模块可能是基于ASP.NET MVC或Web Forms框架实现的。了解这两种框架的基本...