在C#中,一般常用的請求方式,就是利用HttpWebRequest創建請求,返回報文。但是有時候遇到到動態加載的頁面,卻只能抓取部分內容,無法抓取到動態加載的內容。
如果遇到這種的話,推薦使用phantomJS無頭瀏覽器。
開發之前,先准備兩樣東西。
1. phantomJS-2.1.1 官方下載地址:http://phantomjs.org/download.html

2. JS腳本文件,本人命名為codes.js.內容如下。起初我並沒有配置page的settings信息,導致在抓取有些異步頁面卡死。主要原因是由於沒有配置請求頭部信息。
var page = require('webpage').create(), system = require('system');
var url = system.args[1];
var interval = system.args[2];
var settings = {
timeout: interval,
encoding: "gb2312",
operation: "GET",
headers: {
"User-Agent": system.args[3],
"Accept": system.args[4],
"Accept-Language": "zh-CN,en;q=0.7,en-US;q=0.3",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": 1,
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Referer": system.args[5]
}
}
page.settings = settings;
page.open(url, function (status) {
phantom.outputEncoding = "gb2312";
if (status !== 'success') {
console.log('Unable to post!');
phantom.exit();
} else {
setTimeout(function () {
console.log(page.content);
phantom.exit();
}, interval);
}
});
准本完成之后,需要將這兩份文件放到你的項目中。如下:

這些都沒問題了,就可以開始寫后台代碼了。
/// <summary>
/// 利用phantomjs 爬取AJAX加載完成之后的頁面
/// JS腳本刷新時間間隔為1秒,防止頁面AJAX請求時間過長導致數據無法獲取
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetAjaxHtml(string url, HttpConfig config, int interval = 1000)
{
try
{
string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
ProcessStartInfo start = new ProcessStartInfo(path + @"phantomjs\phantomjs.exe");//設置運行的命令行文件問ping.exe文件,這個文件系統會自己找到
start.WorkingDirectory = path + @"phantomjs\";
////設置命令參數
string commond = string.Format("{0} {1} {2} {3} {4} {5}", path + @"phantomjs\codes.js", url, interval, config.UserAgent, config.Accept, config.Referer);
start.Arguments = commond;
StringBuilder sb = new StringBuilder();
start.CreateNoWindow = true;//不顯示dos命令行窗口
start.RedirectStandardOutput = true;//
start.RedirectStandardInput = true;//
start.UseShellExecute = false;//是否指定操作系統外殼進程啟動程序
Process p = Process.Start(start);
StreamReader reader = p.StandardOutput;//截取輸出流
string line = reader.ReadToEnd();//每次讀取一行
string strRet = line;// sb.ToString();
p.WaitForExit();//等待程序執行完退出進程
p.Close();//關閉進程
reader.Close();//關閉流
return strRet;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public class HttpConfig
{
/// <summary>
/// 網站cookie信息
/// </summary>
public string Cookie { get; set; }
/// <summary>
/// 頁面Referer信息
/// </summary>
public string Referer { get; set; }
/// <summary>
/// 默認(text/html)
/// </summary>
public string ContentType { get; set; }
public string Accept { get; set; }
public string AcceptEncoding { get; set; }
/// <summary>
/// 超時時間(毫秒)默認100000
/// </summary>
public int Timeout { get; set; }
public string UserAgent { get; set; }
/// <summary>
/// POST請求時,數據是否進行gzip壓縮
/// </summary>
public bool GZipCompress { get; set; }
public bool KeepAlive { get; set; }
public string CharacterSet { get; set; }
public HttpConfig()
{
this.Timeout = 100000;
this.ContentType = "text/html; charset=" + Encoding.UTF8.WebName;
this.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
this.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
this.AcceptEncoding = "gzip,deflate";
this.GZipCompress = false;
this.KeepAlive = true;
this.CharacterSet = "UTF-8";
}
}
這些也是本人今天才接觸到的,整理下自己的想法。有錯誤之處還希望能夠指出。
