using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using MSXML2; //添加引用 COM - Microsoft XML V3.0-V6.0
using System.Text.RegularExpressions;
namespace EC
{
/// <summary>
/// 远程文件抓取类
/// </summary>
public class GetRemoteObj
{
#region 构造与析构函数
public GetRemoteObj()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
~GetRemoteObj()
{
Dispose();
}
#endregion
#region IDisposable 成员
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
#region 取得文件后缀
/// <summary>
/// 取得文件后缀
/// </summary>
/// <param name="filename">文件名称</param>
/// <returns></returns>
public string GetFileExtends(string filename)
{
string ext = null;
if (filename.IndexOf('.') > 0)
{
string[] fs = filename.Split('.');
ext = fs[fs.Length - 1];
}
return ext;
}
#endregion
#region 获取远程文件源代码
/**********************************
* 函数名称:GetRemoteHtmlCode
* 功能说明:获取远程文件源代码
* 参 数:Url:远程url
* 调用示例:
* GetRemoteObj o = new GetRemoteObj();
* string url = @"http://www.baidu.com";
* string s = o.GetRemoteHtmlCode(url);
* Response.Write(s);
* o.Dispose();
* ********************************/
/// <summary>
/// 获取远程文件源代码
/// </summary>
/// <param name="url">远程url</param>
/// <returns></returns>
public string GetRemoteHtmlCode(string Url)
{
string s = "";
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTP();
_xmlhttp.open("GET", Url, false, null, null);
_xmlhttp.send("");
if (_xmlhttp.readyState == 4)
{
s = System.Text.Encoding.Default.GetString((byte[])_xmlhttp.responseBody);
}
return s;
}
#endregion
#region 保存远程文件
/**********************************
* 函数名称:RemoteSave
* 功能说明:保存远程文件
* 参 数:Url:远程url;Path:保存到的路径
* 调用示例:
* GetRemoteObj o = new GetRemoteObj();
* string s = "";
* string url = @"http://www.baidu.com/img/logo.gif";
* string path =Server.MapPath("Html/");
* s = o.RemoteSave(url,path);
* Response.Write(s);
* o.Dispose();
* ******************************/
/// <summary>
/// 保存远程文件
/// </summary>
/// <param name="Url">远程url</param>
/// <param name="Path">保存到的路径</param>
/// <returns></returns>
public string RemoteSave(string Url, string Path)
{
Random ra = new Random();
string StringFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "." + GetFileExtends(Url);
string StringFilePath = Path + StringFileName;
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTP();
_xmlhttp.open("GET", Url, false, null, null);
_xmlhttp.send("");
if (_xmlhttp.readyState == 4)
{
if (System.IO.File.Exists(StringFilePath))
System.IO.File.Delete(StringFilePath);
System.IO.FileStream fs = new System.IO.FileStream(StringFilePath, System.IO.FileMode.CreateNew);
System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs);
w.Write((byte[])_xmlhttp.responseBody);
w.Close();
fs.Close();
}
else
throw new Exception(_xmlhttp.statusText);
return StringFileName;
}
#endregion
#region 替换网页中的换行和引号
/// <summary>
/// 替换网页中的换行和引号
/// </summary>
/// <param name="HtmlCode">HTML源代码</param>
/// <returns></returns>
public string ReplaceEnter(string HtmlCode)
{
string s = "";
if (HtmlCode == null || HtmlCode == "")
s = "";
else
s = HtmlCode.Replace("\"", "");
s = s.Replace("\r\n", "");
return s;
}
#endregion
#region 替换HTML标签
/// <summary>
/// 替换HTML标签
/// </summary>
/// <param name="HtmlCode">html源代码</param>
/// <returns></returns>
public string RemoveHTML(string HtmlCode)
{
string MatchVale = HtmlCode;
foreach (Match s in Regex.Matches(HtmlCode, "<.+?>"))
{
MatchVale = MatchVale.Replace(s.Value, "");
}
return MatchVale;
}
#endregion
#region 匹配页面的链接
/// <summary>
/// 获取页面的链接正则
/// </summary>
/// <param name="HtmlCode"></param>
/// <returns></returns>
public List<string> GetHref(string HtmlCode)
{
List<string> list = new List<string>();
string Reg = @"(h|H)(r|R)(e|E)(f|F) *= *('|"")?((\w|\\|\/|\.|:|-|_)+)('|""| *|>)?";
foreach (Match m in Regex.Matches(HtmlCode, Reg))
{
list.Add((m.Value).ToLower().Replace("href=", "").Trim());
}
return list;
}
#endregion
#region 匹配页面的图片地址
/// <summary>
/// 匹配页面的图片地址
/// </summary>
/// <param name="HtmlCode"></param>
/// <param name="imgHttp">要补充的http://路径信息</param>
/// <returns></returns>
public string GetImgSrc(string HtmlCode, string imgHttp)
{
string MatchVale = "";
string Reg = @"<img.+?>";
foreach (Match m in Regex.Matches(HtmlCode, Reg))
{
MatchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "||";
}
return MatchVale;
}
/// <summary>
/// 匹配<img src="" />中的图片路径实际链接
/// </summary>
/// <param name="ImgString"><img src="" />字符串</param>
/// <returns></returns>
public string GetImg(string ImgString, string imgHttp)
{
string MatchVale = "";
string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
foreach (Match m in Regex.Matches(ImgString.ToLower(), Reg))
{
MatchVale += (m.Value).ToLower().Trim().Replace("src=", "");
}
return (imgHttp + MatchVale);
}
#endregion
#region 获得指定Html代码中所有超级连接的标题和连接地址
/// <summary>
/// 获得指定Html代码中所有超级连接的标题和连接地址:测试有效 反回Dictionary key-标题 value-地址
/// </summary>
/// <param name="HtmlCode">需要匹配出超级连接的HTML代码</param>
/// <returns></returns>
public Dictionary<string, string> GetCodeHref(string HtmlCode)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
//匹配指定HTML代码中所有的超级连接中的href 和超连接文字内容的正则 有时候需要根据实际情况做小调整如果标题中间有<B>文字</B>的话
string regex = @"\<a.*href\s*=\s*(?:""(?<url>[^""]*)""|'(?<url>[^']*)'|(?<url>[^\>^\s]+)).*\>(?<title>[^\<^\>]*)\<[^\</a\>]*/a\>";
Regex reg1 = new Regex(regex, RegexOptions.IgnoreCase);//创建正则表达式对象
MatchCollection ms1 = reg1.Matches(HtmlCode);//根据正则表达式匹配出所有匹配项返匹配集合
foreach (Match m1 in ms1)//迭代集合获得每个匹配项
{
dic.Add(m1.Groups["title"].Value, m1.Groups["url"].Value);
}
return dic;
}
#endregion
#region 正则获得字符串中开始和结束字符串之间的值
/// <summary>
/// 正则获得字符串中开始和结束字符串之间的值
/// </summary>
/// <param name="str">字符串</param>
/// <param name="s">开始</param>
/// <param name="e">结束</param>
/// <returns></returns>
public string GetRegValue(string str, string s, string e)
{
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
/// <summary>
/// 正则获得字符串中开始和结束字符串之间的值
/// </summary>
/// <param name="str">字符串</param>
/// <param name="s">开始</param>
/// <param name="e">结束</param>
/// <returns></returns>
public List<string> GetRegValueArr(string str, string s, string e)
{
Match m;
List<string> list = new List<string>();
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
for (m = rg.Match(str); m.Success; m = m.NextMatch())
{
list.Add(m.Groups[0].Value);
}
return list;
}
#endregion
#region 替换通过正则获取字符串所带的正则首尾匹配字符串
public string RegReplace(string RegValue, string regStart, string regEnd)
{
string s = RegValue;
if (RegValue != "" && RegValue != null)
{
if (regStart != "" && regStart != null)
{
s = s.Replace(regStart, "");
}
if (regEnd != "" && regEnd != null)
{
s = s.Replace(regEnd, "");
}
}
return s;
}
#endregion
}
}
asp.net(C#)数据采集类
本文转载:CSDN博客