使用HTML Agility Pack从HTML抓取所有文本 [英] Grab all text from html with Html Agility Pack

查看:72
本文介绍了使用HTML Agility Pack从HTML抓取所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入

<html><body><p>foo <a href='http://www.example.com'>bar</a> baz</p></body></html>

输出

foo
bar
baz

我知道 htmldoc.DocumentNode.InnerText ,但是它会提供 foobarbaz -我想一次获取每个文本,而不是一次获取所有文本。

I know of htmldoc.DocumentNode.InnerText, but it will give foobarbaz - I want to get each text, not all at a time.

推荐答案

var root = doc.DocumentNode;
var sb = new StringBuilder();
foreach (var node in root.DescendantNodesAndSelf())
{
    if (!node.HasChildNodes)
    {
        string text = node.InnerText;
        if (!string.IsNullOrEmpty(text))
            sb.AppendLine(text.Trim());
    }
}

这可以满足您的需求,但我不确定如果这是最好的方法。也许您应该遍历DescendantNodesAndSelf之外的其他东西以获得最佳性能。

This does what you need, but I am not sure if this is the best way. Maybe you should iterate through something other than DescendantNodesAndSelf for optimal performance.

这篇关于使用HTML Agility Pack从HTML抓取所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆