本文主要一步一步介绍利用C#抓取页面数据的过程,抓取HTML,获取标题、描述、图片等信息,并去除HTML,希望对大家有所帮助。
private static string GetPageData(string url)
{
if (url == null || url.Trim() == "")
return null;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
Byte[] pageData = wc.DownloadData(url);
return Encoding.Default.GetString(pageData);//.ASCII.GetString
}
Match TitleMatch = Regex.Match(strResponse, "<title>([^<]*)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
title = TitleMatch.Groups[1].Value;
Match Desc = Regex.Match(strResponse, "<meta name="DESCRIPTION" content="([^<]*)">", RegexOptions.IgnoreCase | RegexOptions.Multiline);
strdesc = Desc.Groups[1].Value;
public class HtmlHelper
{
/// <summary>
/// HTML中提取图片地址
/// </summary>
public static List<string> PickupImgUrl(string html)
{
Regex regImg = new Regex(@"<imgb[^<>]*?bsrc[strn]*=[strn]*[""']?[strn]*(?<imgUrl>[^strn""'<>]*)[^<>]*?/?[strn]*>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(html);
一、首先将网页内容整个抓取下来,数据放在byte[]中(网络上传输时形式是byte),进一步转化为String,以便于对其操作,实例如下:
复制代码
private static string GetPageData(string url)
{
if (url == null || url.Trim() == "")
return null;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
Byte[] pageData = wc.DownloadData(url);
return Encoding.Default.GetString(pageData);//.ASCII.GetString
}
二、得到了数据的字符串形式,然后可以对网页进行解析了(其实就是对字符串的各种操作和正则表达式的应用):
常用的的解析还有以下几种:
1.获取标题
复制代码
Match TitleMatch = Regex.Match(strResponse, "<title>([^<]*)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
title = TitleMatch.Groups[1].Value;
2.获取描述信息
复制代码
Match Desc = Regex.Match(strResponse, "<meta name="DESCRIPTION" content="([^<]*)">", RegexOptions.IgnoreCase | RegexOptions.Multiline);
strdesc = Desc.Groups[1].Value;
3.获取图片
复制代码
public class HtmlHelper
{
/// <summary>
/// HTML中提取图片地址
/// </summary>
public static List<string> PickupImgUrl(string html)
{
Regex regImg = new Regex(@"<imgb[^<>]*?bsrc[strn]*=[strn]*[""']?[strn]*(?<imgUrl>[^strn""'<>]*)[^<>]*?/?[strn]*>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(html);










