2009-12-10 130 views
10

我嘗試使用HTML敏捷性包,從裏面獲取的說明文字:HTML敏捷性包

<meta name="description" content="**this is the text i want to extract and store in a string**" /> 

而且有人#2前陣子建議我用HTMLAgilityPack。但我不知道如何使用它,並且我發現的文檔(包括下載中包含的文檔)都有無效的鏈接,因此無法查看文檔。

有人可以幫我解決這個問題嗎?

+1

我很困惑 - 你建HtmlAgilityPack與否?這是不是構建的例子嗎?或核心的DLL?如果後者,你引用了什麼? – 2009-12-10 21:27:32

+0

謝謝馬克。我編輯了我的問題並刪除了該部分以避免更多混淆。現在想想看,這個具體的部分並不是真的與我的問題有關,而是提供了一些信息來說明爲什麼我問這個問題。 – 2009-12-10 21:41:05

+0

我已經能夠在我的應用程序中添加一個引用到dll文件。所以我可以「使用」htmlagility包。 – 2009-12-10 21:56:41

回答

16

其用法與XmlDocument非常相似;您可以在XmlDocument上使用MSDN進行廣泛的概述;您可能還想了解xpath語法(MSDN)。

實施例:

HtmlDocument doc = new HtmlDocument(); 
doc.Load(path); // or .LoadHtml(html); 
HtmlNode node = doc.DocumentNode.SelectSingleNode("//meta[@name='description']"); 
if (node != null) { 
    string desc = node.GetAttributeValue("content", ""); 
    // TODO: write desc somewhere 
} 

的第二個參數GetAttributeValue是默認的情況下,返回的屬性是找不到的。

+0

的值在'node.GetAttributeValue(「content」,「」);'?中使用的第二個字符串參數(空白字符串)是什麼? – Alex 2010-08-19 00:05:13

+0

@AlexW - 我目前沒有該庫「手頭」;什麼是參數調用? – 2010-08-19 08:06:58

+0

不確定參數名稱...稍後會按照定義路徑找出。感謝您在這裏回答,v有用。 – Alex 2010-08-19 11:45:29

0

公共字符串HtmlAgi(字符串URL,字符串鍵) {

var Webget = new HtmlWeb(); 
    var doc = Webget.Load(url); 
    HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key)); 

    if (ourNode != null) 
    { 


      return ourNode.GetAttributeValue("content", ""); 

    } 
    else 
    { 
     return "not fount"; 
    } 

}