Xamarin.AndroidでGoogle Playからアプリ情報をブッコ抜く

提供: MonoBook
ナビゲーションに移動 検索に移動

Xamarin.Androidで強制アップデートを実装する方法はみんなどうやって実装しているのかをググってみていたら、Google Playからスクレイピングでバージョン情報を取れば確実だという記事が多かった。

利点[編集 | ソースを編集]

  • Google Play Consoleにアプリをアップするだけで完結する
  • 自前サーバーが不要なのでスタンドアロンアプリでは活躍する

欠点[編集 | ソースを編集]

  • スクレイピングなのでGoogle Playのデザインが変わると機能しなくなる
    ググると二種類の方法が出てくるので歴史上1回のデザイン変更が発生している模様

実装[編集 | ソースを編集]

とりあえずGoogle Playの画面下部にある情報群をHtmlAgilityPackでブッコ抜いてみる。

現在のデザインではHTMLタグにはその項目固有のidやclassなどは設定されていない。またGoogle Play Consoleでの設定次第で出現項目も変わってくるようだ。そのため「配列の4番目」などと決め打ちにはできない模様。細かい部分はアプリごとに実装しよう。

    using Android.App;
    using Android.Widget;
    using Android.OS;

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using HtmlAgilityPack;

    [Activity(Label = "version_code_and_name", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // スクレイピングなので Google Playのデザインが変われば使えなくなる
            var agent = new HtmlWeb();
            agent.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15";
            var doc = agent.Load("https://play.google.com/store/apps/details?id=skt.android.mayukoyokubariset&hl=ja");

            // パース
            var nodes = doc.DocumentNode
                           .SelectNodes("//div[contains(@class, 'hAyfc')]/span[contains(@class, 'htlgb')]");

            // Google Play Consoleでの設定次第で出現項目が変化するので注意
            Console.WriteLine("更新日   :" + nodes[0].InnerText);
            Console.WriteLine("サイズ   :" + nodes[1].InnerText);
            Console.WriteLine("ダウンロード:" + nodes[2].InnerText);
            Console.WriteLine("バージョン :" + nodes[3].InnerText);
            Console.WriteLine("要件    :" + nodes[4].InnerText);
            Console.WriteLine("レーティング:" + nodes[5].InnerText);
            Console.WriteLine("権限    :" + nodes[6].InnerText);
            Console.WriteLine("レポート  :" + nodes[7].InnerText);
            Console.WriteLine("提供元   :" + nodes[8].InnerText);
            Console.WriteLine("開発元   :" + nodes[9].InnerText);
        }
    }
}

関連項目[編集 | ソースを編集]