【问题标题】:using HtmlAgilityPack to select innerHtml使用 HtmlAgilityPack 选择 innerHtml
【发布时间】:2018-10-29 10:27:57
【问题描述】:

假设我已经关注 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

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

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

Next

【问题讨论】:

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


    【解决方案1】:

    下面是获取 Inner 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);
    
            }
    

    【讨论】:

      【解决方案2】:

      您可以使用SelectNodesDocumentNode 方法从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);
          }
      }
      

      输出:

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 1970-01-01
        • 2012-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        • 1970-01-01
        • 2016-12-28
        相关资源
        最近更新 更多