工作之余,学习了一下正则表达式,鉴于实践是检验真理的唯一标准,于是便写了一个利用正则表达式抓取百度百家文章的例子,具体过程请看下面源码:
一:获取百度百家网页内容
public List<string[]> GetUrl()
{
try
{
string url = "http://baijia.baidu.com/";
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse = webRequest.GetResponse();
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string result = reader.ReadToEnd();
reader.Close();
webResponse.Close();
return AnalysisHtml(result);
}
catch (Exception ex)
{
throw ex;
}
}
二:通过正则表达式筛选
public List<string[]> AnalysisHtml(string htmlContent)
{
List<string[]> list = new List<string[]>();
string strPattern = "<h3><a\\s*.*>(?<Title>[^<]+)</a></h3>.*\\s*<p\\s*class=\"feeds-item-text\">(?<Abstract>[^<]+)<a\\s*href=\"(?<Url>.*)\"\\s*target=\"_blank\"\\s*class=\"feeds-item-more\"\\s*mon=\".*\\s*\">.*\\s*</a></p>";
Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant);
if (regex.IsMatch(htmlContent))
{
MatchCollection matchCollection = regex.Matches(htmlContent);
foreach (Match match in matchCollection)
{
string[] str = new string[];
str[] = match.Groups[].Value;//获取到的是列表数据的标题
str[] = match.Groups[].Value;//获取到的是内容
str[] = match.Groups[].Value;//获取到的是链接到的地址
list.Add(str);
}
}
return list;
}