1. 要想獲取指定連接的數據,那么就得使用HtmlDocument對象,要想使用HtmlDocument對象就必需引用using HtmlAgilityPack;
2. 詳細步驟如下:
步驟一:
獲取鏈接地址內容:
var html =HttpDownLoadHelper.GetUtf8Html("鏈接地址");
HttpDownLoadHelper類中的內容如下:
public class HttpDownLoadHelper
{
/// <summary>
/// 根據URL獲取一個頁面的Html內容
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetUtf8Html(string url)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
var html = wc.DownloadString(url);
return html;
}
}
步驟二:
判斷獲取到的內容是否為空?
步驟三:
獲取數據:
·實例化"HtmlDocument 【HTML文檔】"對象
HtmlDocument doc = new HtmlDocument();
·載入獲取到的內容
doc.LoadHtml(html);
·獲取文檔中的根節點
HtmlNode rootNode = doc.DocumentNode;
·從根節點中通過標簽獲取指定的內容。
HtmlNodeCollection titleNodes = rootNode.SelectNodes("對應的標簽");
存儲數據:
·創建一個存放數據的List集合
List<NewsList> newsList=new List<NewsList>();
NewsList對象的代碼如下:
public class NewsList
{
public string Title { get; set; }
public string Url { get; set; }
}
·將數據添加到集合中:
foreach (var title in titleNodes)
{
NewsList news=new NewsList();
news.Title = title.GetAttributeValue("title", "");
// title是標簽的屬性
news.Url="http://www.yulinu.edu.cn"+title.GetAttributeValue("href", "");
//href是標簽的屬性。
newsList.Add(news);
}
具體事例:【獲取榆林學院首頁中的新聞列表】
HtmlAgilityPack.dll的下載地址:http://htmlagilitypack.codeplex.com/【里面有支持各種.NET Framework的版本的dll。】
·主方法:
public static void Main(string[] args)
{
//創建一個存放新聞的List集合
List<NewsList> newsList=new List<NewsList>();
//根據url獲取一個頁面的Html內容。
var html = HttpDownLoadHelper.GetUtf8Html("http://www.yulinu.edu.cn/news.jsp?urltype=tree.TreeTempUrl&wbtreeid=1036");
//判斷是否為空
if (!string.IsNullOrEmpty(html))
{
HtmlDocument doc = new HtmlDocument(); //實例化html實例對象
doc.LoadHtml(html);//載入html文檔
HtmlNode rootNode = doc.DocumentNode; //獲取文檔中的根節點
//從根節點中通過標簽獲取指定的內容。
HtmlNodeCollection titleNodes = rootNode.SelectNodes("//div[@class='Classbox List']/ul/li/a");
foreach (var title in titleNodes)
{
NewsList news=new NewsList();
news.Title = title.GetAttributeValue("title", "");
news.Url = "http://www.yulinu.edu.cn" + title.GetAttributeValue("href", "");
newsList.Add(news);
}
}
//輸出標題和地址
foreach (var list in newsList)
{
Console.WriteLine("新聞標題為:{0},新聞鏈接地址為:{1}",list.Title,list.Url);
}
Console.WriteLine("總共有{0}條新聞",newsList.Count);
Console.ReadKey();
}
·HttpDownLoadHelper代碼如下:
public class HttpDownLoadHelper
{
/// <summary>
/// 根據URL獲取一個頁面的Html內容
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetUtf8Html(string url)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
var html = wc.DownloadString(url);
return html;
}
}
·NewsList代碼如下:
public class NewsList
{
public string Title { get; set; }
public string Url { get; set; }
}