程序员兴趣站建成记 我爱篮球网
我是2012年夏毕业,到现在正式工作刚满一年,在这一年中也取得了一定进步。公司主要从事.net网站开发,我们都用的是MVC,参与了几个大型的项目,企业站也做了几个。
每天对着电脑的工作也许不是我想要的,我也算一个坐不住的人,我爱好篮球,目前唯一的爱好了,经常看NBA,就萌生了自己建一个有关NBA的网站了,可是工作中,自己只写C#代码,几乎不写html和js,就硬着头皮写了写,很丑,但目前想要的功能还是实现了。
说说网站实现吧,网站用MVC开发,数据库是mysql,NBA网站最重要的是数据,数据跟新很快,自己也没那个精力慢慢往网站里填数据,那就得抓数据了,利用WebClient抓取网站内容。
/// <summary>
/// 获取内容
/// </summary>
private static string GetPageContent(Uri uri, Encoding encoding)
{
WebClient webclient = new WebClient();
try
{
webclient.Encoding = encoding;
return webclient.DownloadString(uri);
}
catch
{
return string.Empty;
}
finally
{
webclient.Dispose();
}
}
获取网站的内容后,解析网站结构,利用正则表达式获取自己需要的数据,网上找到一个类,利用正则解析html字符串的,参考了http://www.cnblogs.com/lucc/archive/2010/05/18/1738718.html这篇博客。
/// <summary>
/// 在文本html的文本查找标志名为tagName,并且属性attrName的值为attrValue的所有标志
/// 例如:FindTagByAttr(html, "div", "class", "demo")
/// 返回所有class为demo的div标志
/// </summary>
public static List<HtmlTag> FindTagByAttr(String html, String tagName, String attrName, String attrValue)
{
String format = String.Format(@"<{0}\s[^<>]*{1}\s*=\s*(\x27|\x22){2}(\x27|\x22)[^<>]*>", tagName, attrName, attrValue);
return FindTag(html, tagName, format);
}
public static List<HtmlTag> FindTag(String html, String name, String format)
{
Regex reg = new Regex(format, RegexOptions.IgnoreCase);
Regex tagReg = new Regex(String.Format(@"<(\/|)({0})(\s[^<>]*|)>", name), RegexOptions.IgnoreCase);
List<HtmlTag> tags = new List<HtmlTag>();
int start = 0;
while (true)
{
Match match = reg.Match(html, start);
if (match.Success)
{
start = match.Index + match.Length;
Match tagMatch = null;
int beginTagCount = 1;
while (true)
{
tagMatch = tagReg.Match(html, start);
if (!tagMatch.Success)
{
tagMatch = null;
break;
}
start = tagMatch.Index + tagMatch.Length;
if (tagMatch.Groups[1].Value == "/") beginTagCount--;
else beginTagCount++;
if (beginTagCount == 0) break;
}
if (tagMatch != null)
{
HtmlTag tag = new HtmlTag(name, match.Value, html.Substring(match.Index + match.Length, tagMatch.Index - match.Index - match.Length));
tags.Add(tag);
}
else
{
break;
}
}
else
{
break;
}
}
return tags;
}
获取数据后,接着就是入库了。接着就是前台展示。网站建成http://www.5ailanqiu.com

浙公网安备 33010602011771号