2010-05-31 6 views
3

Je veux extraire du texte significatif d'un document html et j'utilisais html-agility-pack pour le même. Voici mon code:HtmlAgilityPack donnant des problèmes avec html malformé

string convertedContent = HttpUtility.HtmlDecode(
    ConvertHtml(HtmlAgilityPack.HtmlEntity.DeEntitize(htmlAsString)) 
); 

ConvertHtml:

public string ConvertHtml(string html) 
{ 
    HtmlDocument doc = new HtmlDocument(); 
    doc.LoadHtml(html); 

    StringWriter sw = new StringWriter(); 
    ConvertTo(doc.DocumentNode, sw); 
    sw.Flush(); 
    return sw.ToString(); 
} 

ConvertTo:

public void ConvertTo(HtmlAgilityPack.HtmlNode node, TextWriter outText) 
{ 
    string html; 
    switch (node.NodeType) 
    { 
     case HtmlAgilityPack.HtmlNodeType.Comment: 
      // don't output comments 
      break; 

     case HtmlAgilityPack.HtmlNodeType.Document: 
      foreach (HtmlNode subnode in node.ChildNodes) 
      { 
       ConvertTo(subnode, outText); 
      } 
      break; 

     case HtmlAgilityPack.HtmlNodeType.Text: 
      // script and style must not be output 
      string parentName = node.ParentNode.Name; 
      if ((parentName == "script") || (parentName == "style")) 
       break; 

      // get text 
      html = ((HtmlTextNode)node).Text; 

      // is it in fact a special closing node output as text? 
      if (HtmlNode.IsOverlappedClosingElement(html)) 
       break; 

      // check the text is meaningful and not a bunch of whitespaces 
      if (html.Trim().Length > 0) 
      { 
       outText.Write(HtmlEntity.DeEntitize(html) + " "); 
      } 
      break; 

     case HtmlAgilityPack.HtmlNodeType.Element: 
      switch (node.Name) 
      { 
       case "p": 
        // treat paragraphs as crlf 
        outText.Write("\r\n"); 
        break; 
      } 

      if (node.HasChildNodes) 
      { 
      foreach (HtmlNode subnode in node.ChildNodes) 
      { 
       ConvertTo(subnode, outText); 
      } 
      } 
      break; 
    } 
} 

Maintenant, dans certains cas, lorsque les pages html sont malformés (par exemple la page suivante - http://rareseeds.com/cart/products/Purple_of_Romagna_Artichoke-646-72.html a une meta-tag mal formé comme <meta content="text/html; charset=uft-8" http-equiv="Content-Type">) [Note "uft" au lieu de utf] mon code vomit au moment où j'essaye de charger le document html. Quelqu'un peut-il me suggérer comment puis-je surmonter ces pages html malformées et encore extraire le texte pertinent d'un document html?

Merci, Kapil

Répondre

3

Comme il est dit dans la page du projet HtmlAgilityPack « L'analyseur est très tolérant avec « monde réel » HTML malformé ». Mais le genre d'erreur que vous décrivez est trop sérieux pour être corrigé. Vous pouvez définir le codage par défaut avec:

HtmlDocument doc = new HtmlDocument(); 
doc.OptionDefaultStreamEncoding = Encoding.UTF8; 
Questions connexes