最近作了一个项目,要求获取各大主流网页上的关键信息,本人之前了解过网页爬虫的知识,因此想到了网页爬虫了实现功能css
第一次尝试:html
采用webclient获取远程网页的内容,而后采用正则表达式进行过滤node
但,因为正则表达式对我来讲,书写起来比较复杂,研究个大半个月,一点进展都没有,天天看着正则表达式像看天书(回头须要向正则牛逼的人请教一下)web
第一次尝试失败,项目立刻就要验收了,这个功能一直卡壳了,,,,,,,,正则表达式
忽然有一次,在网上看到了有人说起到了HtmlAgilityPack这个开源的工具包,本想着试一下的态度(由于我对这个网页解析已经不抱有但愿了)网页爬虫
仅仅有了几行的代码,竟然跟个人需求同样实现了,万分高兴(此处使用HtmlAgilityPack须要学习一下xpath的一点知识,不过那些都很简单,比起正则太easy了)网络
好了,废话很少说,上代码工具
一、去官网上下载一个HtmlAgilityPack包,地址:http://htmlagilitypack.codeplex.com/学习
二、根据本身项目的.net版本,选择适合的版本,引入项目ui
三、开始写代码了
HtmlAgilityPack基本跟全部的类同样,直接使用里面的方法和属性就行,具体能够参考官网
//获取网页指定内容 public void GetHtml() { string htmlpath = "http://kaijiang.aicai.com/fcssq/"; //建立对象 HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); WebClient webclient = new WebClient(); webclient.Credentials = CredentialCache.DefaultCredentials;//网络凭证 Byte[] pageData = webclient.DownloadData(htmlpath); // string pagehtml = Encoding.Default.GetString(pageData); //默认编码 string pagehtml = Encoding.UTF8.GetString(pageData);//UTF-8编码 //用htmlagilitypack 解析网页内容 //加载html doc.LoadHtml(pagehtml); //经过xpath 选中指定元素;xpath 参考:http://www.w3school.com.cn/xpath/xpath_syntax.asp HtmlAgilityPack.HtmlNode htmlnode = doc.DocumentNode.SelectSingleNode("//div[@id='jq_openResult']"); StringBuilder sb = new StringBuilder(); string s = ""; HtmlAgilityPack.HtmlNodeCollection nodecollection = htmlnode.ChildNodes; for (int i = 0; i < nodecollection.Count; i++) { if (nodecollection[i].InnerText.Trim()!="") { TextBox1.Text += nodecollection[i].InnerText + "-"; } } TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1); Console.WriteLine(s); }
至此,HtmlAgilityPack就彻底按照本身的要求解析出来了网页上的任何你想要的,是否是很神奇~~