好吧,我对 HTMLAgilityPack 中使用的 XPath 查询真的很陌生。
那么让我们考虑这个页面 http://health.yahoo.net/articles/healthcare/what-your-favorite-flavor-says-about-you .我想要的是仅提取页面内容,不提取任何其他内容。
为此,我首先删除了脚本和样式标签。
Document = new HtmlDocument();
Document.LoadHtml(page);
TempString = new StringBuilder();
foreach (HtmlNode style in Document.DocumentNode.Descendants("style").ToArray())
{
style.Remove();
}
foreach (HtmlNode script in Document.DocumentNode.Descendants("script").ToArray())
{
script.Remove();
}
之后,我尝试使用//text() 获取所有文本节点。
foreach (HtmlTextNode node in Document.DocumentNode.SelectNodes("//text()"))
{
TempString.AppendLine(node.InnerText);
}
然而,不仅我得到的不仅仅是文本,我还得到了很多/r/n 字符。
在这方面我需要一些指导。
最佳答案
如果您认为script
和style
节点只有子节点的文本节点,您可以使用这个XPath 表达式来获取script 中没有的文本节点
或 style
标签,这样您就不需要事先删除节点:
//*[not(self::script or self::style)]/text()
您可以使用 XPath 的 normalize-space()
进一步排除只有空格的文本节点:
//*[not(self::script or self::style)]/text()[not(normalize-space(.)="")]
或较短的
//*[not(self::script or self::style)]/text()[normalize-space()]
但是您仍然会得到可能有前导或尾随空格的文本节点。这可以按照@aL3891 的建议在您的应用程序中处理。
关于c# - 使用 HTMLAgilityPack 仅提取页面文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343231/