我想从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();
}
的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;
}
}
现在在某些情况下,当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”而不是utf]我的代码是在我试图加载html文档的时候呕吐。
有人可以建议我如何克服这些格式错误的html页面并仍然从html文档中提取相关文本?
谢谢, 卡皮尔
答案 0 :(得分:3)
正如在HtmlAgilityPack项目页面中所说的那样“解析器对'真实世界'格式错误的HTML非常宽容”。但是你描述的那种错误太严重了,可能无法纠正。您可以使用以下命令设置默认编码:
HtmlDocument doc = new HtmlDocument();
doc.OptionDefaultStreamEncoding = Encoding.UTF8;