【Selenium】C#で自動ログインするサンプルプログラム【Chrome】
作業を自動化したいとき、サイトにログインする必要があることも多いです。そこで、自動でログインする方法について、サンプルプログラムを交えて解説します。
今回はC#編です。Pythonでの手順は以下の記事をご覧ください。
作業環境
- Windows10
- Visual Studio
- .NET Framework 4.7.2
Visual StudioでC#を使えるようにする方法はこちらをご覧ください。
事前準備
Visual Studioの「NuGetパッケージの管理」から以下のパッケージのインストールが必要です。
サンプルプログラム
楽天e-naviにログインするサンプルプログラム
楽天e-naviにログインするサンプルプログラムです。
他のサイトではURLはもちろん、ログインIDやパスワードの入力領域の取得方法が変わってきます。
using System; using System.IO; using System.Reflection; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace SeleniumTest { class MainClass { const string LOGIN_ID = "xxxx"; const string PASSWORD = "xxxx"; public static void Main(string[] args) { // Webドライバーのインスタンス化 IWebDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); driver.Navigate().GoToUrl(@"https://www.rakuten-card.co.jp/e-navi/"); // URLに移動 IWebElement mailAddress = driver.FindElement(By.Name("u")); // メールアドレスの入力領域を取得 IWebElement password = driver.FindElement(By.Name("p")); // パスワードの入力領域を取得 mailAddress.Clear(); // メールアドレスの入力領域を初期化 password.Clear(); // パスワードの入力領域を初期化 mailAddress.SendKeys(LOGIN_ID); // メールアドレスを入力 password.SendKeys(PASSWORD); // パスワードを入力 mailAddress.Submit(); driver.Quit(); } } }
21,22行目の要素の取得はWebページにアクセスし、右クリックメニューの「検証」を使用して調べます。詳細はこちらのサイトが参考になります。
岡三オンライン証券にログインするサンプルプログラム
こちらは岡三オンライン証券のサイトにログインするサンプルプログラムです。
using System; using System.IO; using System.Reflection; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace SeleniumTest { class MainClass { const string LOGIN_ID = "xxxx"; const string PASSWORD = "xxxx"; public static void Main(string[] args) { // Webドライバーのインスタンス化 IWebDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); // URLに移動します。 driver.Navigate().GoToUrl(@"https://www.okasan-online.co.jp/login/jp/"); IWebElement loginId = driver.FindElement(By.Name("account")); // メールアドレスの入力領域を取得 IWebElement password = driver.FindElement(By.Name("pass")); // パスワードの入力領域を取得 loginId.Clear(); // メールアドレスの入力領域を初期化 password.Clear(); // パスワードの入力領域を初期化 loginId.SendKeys(LOGIN_ID); // メールアドレスを入力 password.SendKeys(PASSWORD); // パスワードを入力 driver.FindElement(By.Name("buttonLogin")).Submit(); driver.FindElement(By.Name("buttonOK")).Click(); driver.Quit(); } } }