2013-05-12 40 views
0

許多網頁沒有描述元標記,例如維基百科。 Here表示,如果標籤不存在,那麼搜索引擎就像谷歌獲得更短的段落。我不知道如何使用HtmlAgilityPack實現這種行爲?如果元標記爲空或不存在,則從文本中獲取較短的段落。下面的例子工作時說明存在。如果元標記不存在,如何提取描述?

String description = (from x in content.DocumentNode.Descendants() 
         where x.Name.ToLower() == "meta" 
         && x.Attributes["name"] != null 
         && x.Attributes["name"].Value.ToLower() == "description" 
         select x.Attributes["content"].Value).FirstOrDefault(); 

回答

0

您可以使用XPath,這樣的事情,包裹在一個方法:

static string GetMetaDescription(HtmlDocument doc) 
    { 
     // get a META element recursively in the document 
     // which has a NAME attribute equal to 'description' 
     // and a non empty CONTENT attribute. 
     HtmlNode node = doc.DocumentNode.SelectSingleNode("//meta[@name='description' and @content]"); 
     if (node == null) 
      return null; 

     // get the value of the CONTENT attribute 
     return node.GetAttributeValue("content", null); 
    } 
相關問題