博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网页抓取
阅读量:7063 次
发布时间:2019-06-28

本文共 3617 字,大约阅读时间需要 12 分钟。

之前做聊天室时,由于在聊天室中提供了新闻阅读的功能,写了一个从网页中抓取信息(如最新的头条新闻,新闻的来源,标题,内容等)的类,本文将介绍如何使用这个类来抓取网页中需要的信息。本文将以抓取博客园首页的博客标题和链接为例:

image

上图显示的是博客园首页的DOM树,显然只需提取出class为post_item的div,再重中提取出class为titlelnk的a标志即可。这样的功能可以通过以下函数来实现:

/// /// 在文本html的文本查找标志名为tagName,并且属性attrName的值为attrValue的所有标志/// 例如:FindTagByAttr(html, "div", "class", "demo")/// 返回所有class为demo的div标志/// public static List
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
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
tags = new List
(); 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;}

有了以上函数,就可以提取需要的HTML标志了,要实现抓取,还需要一个下载网页的函数:

public static String GetHtml(string url){    try    {        HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;        req.Timeout = 30 * 1000;        HttpWebResponse response = req.GetResponse() as HttpWebResponse;        Stream stream = response.GetResponseStream();        MemoryStream buffer = new MemoryStream();        Byte[] temp = new Byte[4096];        int count = 0;        while ((count = stream.Read(temp, 0, 4096)) > 0)        {            buffer.Write(temp, 0, count);        }        return Encoding.GetEncoding(response.CharacterSet).GetString(buffer.GetBuffer());    }    catch    {        return String.Empty;    }}

以下以抓取博客园首页的文章标题和链接为例,介绍如何使用HtmlTag类来抓取网页信息:

class Program{    static void Main(string[] args)    {        String html = HtmlTag.GetHtml("http://www.cnblogs.com");        List
tags = HtmlTag.FindTagByAttr(html, "div", "id", "post_list"); if (tags.Count > 0) { List
item_tags = tags[0].FindTagByAttr("div", "class", "post_item"); foreach (HtmlTag item_tag in item_tags) { List
a_tags = item_tag.FindTagByAttr("a", "class", "titlelnk"); if (a_tags.Count > 0) { Console.WriteLine("标题:{0}", a_tags[0].InnerHTML); Console.WriteLine("链接:{0}", a_tags[0].GetAttribute("href")); Console.WriteLine(""); } } } }}

运行结果如下:

image

来源:http://www.cnblogs.com/lucc/archive/2010/05/18/1738718.html  

你可能感兴趣的文章
Citrix XenDesktop 引发的学案(四)-与“您的虚拟桌面”之间的连接失败,状态(1030)...
查看>>
mysql-5.6的GTID复制的实现
查看>>
6421B Lab10 网络文件和打印服务的配置与故障排除
查看>>
快速安装配置zabbix_agent端
查看>>
DNS服务的配置与管理(5) 配置转发器
查看>>
AIP(Azure 信息保护)之一:启用与激活服务
查看>>
一步步学WebSocket(3)WebSocket协议格式
查看>>
linux更新内核
查看>>
通过mdadm命令调用内核MD模块实现软Raid
查看>>
为RemoteApp的登录用户(域用户)添加输入法的方法
查看>>
分享Open-E DSS V7 应用系列十篇!
查看>>
分享Silverlight/Windows8/WPF/WP7/HTML5一周学习导读(5月6日-5月12日)
查看>>
javascript框架概览备忘
查看>>
产品与技术(人员)间的职责关系
查看>>
企业云桌面-13-为企业新建组织单位
查看>>
SystemCenter2012SP1实践(5)SCVMM管理HyperV
查看>>
Ext JS添加子组件的误区
查看>>
微软私有云分享(R2)27维护窗口的使用
查看>>
Mac 平台下功能强大的Shimo软件使用指南
查看>>
永远不要对一个外行聊你的专业
查看>>