1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# + Html Agility Pack で基本的なことを少し触ってみる

Last updated at Posted at 2022-07-16

目的

Yahoo!ニュースの主要トピックスに対してHtml Agility Packを試したときのメモ
・Copy XPathの出力+Linqの組み合わせ

追加パッケージ

.NET6でプロジェクトを作成後
プロジェクト -> NuGetパッケージの管理より以下を追加する(作成日のバージョン)

HtmlAgilityPack(1.11.43)
System.Text.Encoding.CodePages(6.0.0)

CSのサンプルコード

    using System.Net.Http;
    using System.Diagnostics;
    using HtmlAgilityPack;

    private async void btnYahooNews_Click(object sender, EventArgs e)
    {
        var builder = new UriBuilder("https://news.yahoo.co.jp/");

        var client = new HttpClient();
        client.Timeout = TimeSpan.FromSeconds(10.0);

        string htmlString = await client.GetStringAsync(builder.Uri);

        HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();

        html.LoadHtml(htmlString);

        var root = html.DocumentNode;
        //
        // XPathを使用してトピック全8項目を取得する
        //
        var nodes = root.SelectNodes("//*[@id=\"uamods-topics\"]/div/div/div/ul/li[1 or 8]/a")
            .Select(s => new { ctxt = s.InnerText.Trim(), href = s.Attributes["href"].Value.Trim() });

        foreach (var item in nodes)
        {
            //Debug.WriteLine(item.ctxt + " " + item.href);

            //
            // 各記事へ移動する -> 記事全文を読むのURLを取得する
            //
            var ndbuilder = new UriBuilder(item.href);

            var ndclient = new HttpClient();
            ndclient.Timeout = TimeSpan.FromSeconds(10.0);

            string ndString = await ndclient.GetStringAsync(ndbuilder.Uri);

            HtmlAgilityPack.HtmlDocument ndhtml = new HtmlAgilityPack.HtmlDocument();
            ndhtml.LoadHtml(ndString);

            var ndroot = ndhtml.DocumentNode;
            // 記事全文を読む
            var node = ndroot.SelectNodes("//*[@id=\"uamods-pickup\"]/div[2]/div/p/a")
                .Select(s => new { ctxt = s.InnerText.Trim(), href = s.Attributes["href"].Value.Trim()});

            foreach (var nd in node)
            {
                Debug.WriteLine(nd.ctxt + " " + nd.href);
            }
        }
    }

参考にしたのは以下のサイト

C#でHTMLを解析する(Html Agility Packライブラリ)
Html Agility Packを使ってWebページをスクレイピングするには?[C#、VB]
Html Agility Pack を使用してサイトのHTMLを解析する
C# + AngleSharp で基本的なことを少し触ってみる
Windows10 + Python3 + BeautifulSoup4 を試してみる

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?