seleniumを使ってC#でGoogle Chromeの自動操作をする


やりたいこと

1.Google Chromeでhttps://www.google.co.jp/を開く
2.テキストボックスに"Selenium"を入力
3.「Google 検索」ボタンをクリック

環境

  • Windows 7
  • Google Chrome 77
  • Visual Studio Community 2019

準備

1.C#のコンソールアプリでプロジェクトを作成
2.NuGetパッケージ管理にて以下をインストール
- Selenium.WebDriver
- Selenium.WebDriver.ChromeDriver

ソース

Program.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumChromeSample
{
    class Program
    {
        /// <summary>
        /// SeleniumでIEを自動操作するサンプル
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
            IWebElement textbox;
            IWebElement findbuttom;

            //Webページを開く
            driver.Navigate().GoToUrl("https://www.google.co.jp/");

            //検索ボックス
            textbox = driver.FindElement(By.Name("q"));
            //検索ボックスに検索ワードを入力
            textbox.SendKeys("Selenium");

            //検索ボタン
            findbuttom = driver.FindElement(By.Name("btnK"));
            //検索ボタンをクリック
            findbuttom.Click();
        }
    }
}

参考

Selenium - Web Browser Automation