htmlドキュメントから意味のあるテキストを抽出したいのですが、同じようにhtml-agility-packを使用していました。これが私のコードです:
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();
}
に変換:
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;
}
}
これで、htmlページの形式が正しくない場合があります(たとえば、次のページ-http ://rareseeds.com/cart/products/Purple_of_Romagna_Artichoke-646-72.htmlには次のような形式の悪いメタタグがあります<meta content="text/html; charset=uft-8" http-equiv="Content-Type">
)[代わりに「uft」に注意してくださいof utf] htmlドキュメントを読み込もうとしているときに、コードが壊れています。
誰かが私にこれらの不正な形式のhtmlページを克服し、それでもhtmlドキュメントから関連するテキストを抽出する方法を提案できますか?
ありがとう、カピル