NSoup是一個開源框架,是JSoup(Java)的.NET移植版本
1、直接用起來
NSoup.Nodes.Document htmlDoc = NSoup.NSoupClient.Parse(HTMLString); //無需實例化
NSoup的強大之處在於可以用類似js的方法來獲取節點元素
通過元素類型獲取元素GetElementByTag("p")
NSoup.Select.Elements ele= htmlDoc.GetElementsByTag(TbTag.Text); foreach (var item in ele) { if (item.Attr("class") == "col-sm-4 col-xs-6 listtit1") //通過Attr(""href)可以獲取元素的屬性 { sb.AppendLine(item.Text()); //通過Text()方法可以獲取元素中的文本內容 } }
2、做了一個winform的小demo
關鍵代碼:
下面以提取一個html代碼中211大學名和地點的為例:
private void GetHtml_Click(object sender, EventArgs e) { //獲取指定地址的Html代碼 TbCode.Text = ""; string url = TbUrl.Text.Trim(); WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; string html = client.DownloadString(url); TbCode.Text = html; } private void Analysis_Click(object sender, EventArgs e) { NSoup.Nodes.Document htmlDoc = NSoup.NSoupClient.Parse(TbCode.Text); NSoup.Select.Elements ele= htmlDoc.GetElementsByTag(TbTag.Text); System.Text.StringBuilder sb=new StringBuilder(); foreach (var item in ele) { sb.AppendLine(item.Text()); foreach (var item1 in item.NextElementSibling.Children) { if (item1.Attr("class") == "col-sm-4 col-xs-6 listtit1") { sb.AppendLine(item1.Text()); } } } TbElement.Text = sb.ToString(); }
html代碼片段(因篇幅原因未貼全):
<h4>安徽</h4> <ul class="list-unstyled clearfix"> <li class="col-sm-4 col-xs-6 listtit1"><a href="/daxue/detail/detail3712.html">合肥工業大學</a></li> <li class="col-sm-4 col-xs-6 listtit1"><a href="/daxue/detail/detail3715.html">中國科學技術大學</a></li> <li class="col-sm-4 col-xs-6 listtit1"><a href="/daxue/detail/detail3716.html">安徽大學</a></li> </ul>
效果(標簽類型h4):
3、插入數據庫代碼示例(提取專業名和編號):
private void BtnInsert_Click(object sender, EventArgs e) { NSoup.Nodes.Document htmlDoc = NSoup.NSoupClient.Parse(TbCode.Text); NSoup.Select.Elements eles = htmlDoc.GetElementsByTag(TbTag.Text); string connectionString = @"這裡是連接字符串"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); foreach (var item in eles) { if (item.Attr("width") == "20%" && item.NextElementSibling
!= null && item.Text().Length > 4) { string sql = "insert into Major (mId,mName) values
('" +item.Text() + "','" + item.NextElementSibling.Text() + "')"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.ExecuteNonQuery(); } } } conn.Close(); } }
Html代碼片段:
<table class="cla" border="0" cellspacing="1" cellpadding="0" width="100%" bgcolor="#dedede"> <tbody> <tr class="scon">
<td bgcolor="#ffffff" width="20%"><strong>0101</strong></td>
<td bgcolor="#ffffff" height="30"><strong>哲學類</strong></td>
</tr> <tr><td bgcolor="#ffffff" width="20%">010101</td>
<td bgcolor="#ffffff" height="30"><span class="pl20">哲學</span></td></tr> <tr><td bgcolor="#ffffff" width="20%">010102</td>
<td bgcolor="#ffffff" height="30"><span class="pl20">邏輯學</span></td></tr> <tr><td bgcolor="#ffffff" width="20%">010103K</td>
<td bgcolor="#ffffff" height="30"><span class="pl20">宗教學</span></td></tr> </tbody> </table>
方法有很多種,就不一一列舉了,可以多試幾種,當然熟悉Python的朋友就不必這麼麻煩了,Python有更專業的html解析器,有時間可以了解一下