C# AngleSharpでHTMLファイルを解析する

  • 作成日 2021.10.12
  • 更新日 2022.03.12
  • C#
C# AngleSharpでHTMLファイルを解析する

C#で、AngleSharpでHTMLファイルを解析するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • .net core 3.1
  • Microsoft Visual Studio Community 2019 Version 16.7.1

AngleSharpでHTMLファイルを解析

AngleSharpでHTMLファイルを解析するには、まずはnugetで入手します。

Install-Package AngleSharp

以下は、AngleSharpを使用してHTMLファイルを解析するだけのコードとなります。

htmlファイル( index.html )

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>test</title>
  </head>
  <body>
    <p id="id-hoge">id-hoge</p>
    <p class="class-hoge">class-hoge1</p>
    <p class="class-hoge">class-hoge2</p>
    <p class="class-hoge">class-hoge3</p>
  </body>
</html>

サンプルコード

using System;
using System.IO;
using AngleSharp.Html.Parser;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // htmlファイルを読み込む
                var html = File.ReadAllText(@"C:\html\index.html", System.Text.Encoding.UTF8);
                var parser = new HtmlParser();

                // htmlをパース
                var doc = parser.ParseDocument(html);

                // idを指定
                var idHoge = doc.GetElementById("id-hoge");
                Console.WriteLine($"id「id-p」の要素は{idHoge.TextContent}");

                // classを指定
                var classHoge = doc.GetElementsByClassName("class-hoge");

                foreach (var v in classHoge)
                {                    
                    Console.WriteLine($"class「class-hoge」の要素は{v.TextContent}");
                }
            }
            catch (NullReferenceException e)
            {
                System.Console.WriteLine("存在しない要素を指定してます" + e.ToString());
            }
            catch (IOException e)
            {
                System.Console.WriteLine("ファイルが存在しません" + e.ToString());
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
        }
    }
}

実行結果

また、存在しない要素を指定すると「NullReferenceException」が発生します。

System.NullReferenceException: Object reference not set to an instance of an object.