从网页中提取内容

时间:2013-08-21 10:58:14

标签: c# .net xpath html-parsing html-agility-pack

我正在尝试使用HTMLagilitypack从网页中提取所有内容。

foreach (HtmlTextNode node in doc.DocumentNode.SelectNodes("//text()"))
{
    sb.AppendLine(node.Text);
}

当我尝试使用上述代码解析google.com时,我会获得大量的javascript。我想要的是在hp标签中提取网页中的内容。就像在这个页面上回答问题,回答,评论并删除其他所有内容一样。

我是XPath的新手,并不知道在哪里继续前进。所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

您可以按名称过滤不需要的代码,并将其从文档中删除。

        doc = page.Load("http://www.google.com");
        doc.DocumentNode.Descendants().Where(n => n.Name == "script" || n.Name == "style").ToList().ForEach(n => n.Remove());

答案 1 :(得分:0)

您可以使用此XPath表达式:

//body//*[local-name() != 'script']/text()

只需body内的元素并跳过script元素

相关问题