2013-05-12 42 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); 
    }