使用HtmlAgilityPack选择innerHtml

时间:2018-10-29 10:27:58

标签: c# html vb.net html-agility-pack

让我说我遵循html文档

<div class=" wrap_body text_align_left" style="">
  <div class="some"> hello </div>
  <div class="someother"> world </div>
  hello world
</div>

我要提取这个

      <div class="some"> hello </div>
      <div class="someother"> world </div>
      hello world

使用HtmlAgilityPack和c#或vb.net提取的最佳方法是什么? 这是我的代码,直到完成,但有些困难。 谢谢!

For Each no As HtmlAgilityPack.HtmlNode In docs.DocumentNode.SelectNodes("//div[contains(@class,'wrap_body')]")
    Dim attr As String = no.GetAttributeValue("wrap_body", "")

Next

2 个答案:

答案 0 :(得分:2)

以下是获取内部HTML的示例

var html =
        @"<body>
            <div class='wrap_body text_align_left' style=''>
  <div class='some'> hello </div>
  <div class='someother'> world </div>
  hello world
</div>
        </body>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//body/div");

        foreach (var node in htmlNodes)
        {

            Console.WriteLine(node.InnerHtml);

        }

答案 1 :(得分:1)

您可以使用SelectNodes方法中的DocumentNode从html检索特定节点。

class Program
{
    static void Main(string[] args)
    {
        string htmlContent = File.ReadAllText(@"Your path to html file"); ;

        HtmlDocument doc = new HtmlDocument();

        doc.LoadHtml(htmlContent);

        var innerContent = doc.DocumentNode.SelectNodes("/div").FirstOrDefault().InnerHtml;

        Console.WriteLine(innerContent);
    }
}

输出:

enter image description here