ajax抓取网页内容(1.JS脚本文件-2.1.1官方下载地址(图))

优采云 发布时间: 2021-12-01 11:07

  ajax抓取网页内容(1.JS脚本文件-2.1.1官方下载地址(图))

  在C#中,常用的请求方法是使用HttpWebRequest创建请求并返回消息。但是,有时遇到动态加载的页面时,只能抓取部分内容,而无法抓取动态加载的内容。

  如果遇到这种情况,建议使用phantomJS无头浏览器。

  在开发之前,准备两件事。

  1. phantomJS-2.1.1 官方下载地址:

  

  2. JS脚本文件,我自己命名为codes.js。内容如下。一开始我没有配置页面的设置信息,导致一些异步页面在爬行的时候卡住了。主要原因是没有配置请求头信息。

  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);

}

});

  草稿完成后,您需要将这两个文件放入您的项目中。如下:

  

  如果这些都没有问题,就可以开始编写后台代码了。

  ///

/// 利用phantomjs 爬取AJAX加载完成之后的页面

/// JS脚本刷新时间间隔为1秒,防止页面AJAX请求时间过长导致数据无法获取

///

///

///

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

{

///

/// 网站cookie信息

///

public string Cookie { get; set; }

///

/// 页面Referer信息

///

public string Referer { get; set; }

///

/// 默认(text/html)

///

public string ContentType { get; set; }

public string Accept { get; set; }

public string AcceptEncoding { get; set; }

///

/// 超时时间(毫秒)默认100000

///

public int Timeout { get; set; }

public string UserAgent { get; set; }

///

/// POST请求时,数据是否进行gzip压缩

///

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";

}

}

  这些是我今天才接触到的,所以整理了一下思路。我希望我能指出哪里有错误。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线