LoginSignup
1
4

More than 3 years have passed since last update.

【C#】seleninmでスクレイピング

Last updated at Posted at 2020-07-26

参考

Seleniumブラウザー自動化プロジェクト

PHPやPythonでスクレイピングの勉強をしていたのですが、
「Selenium」が様々な言語に対応しているという事と、
以前クラウドソーシングでC#の「Selenium」があったので、サンプルを記載しました。

事前準備

Nugetパッケージで以下をインストールします。

・Selenium.Support
・Selenium.WebDriver

Chromeドライバをダウンロードします。

Chromeドライバから、自分の端末のChromeとバージョンが一致するものをダウンロードしてください。
今回のサンプルでは、「C:\webdriver」にフォルダに配置しています。

コード

以下は、amazonのサイトで、検索結果を取得するサンプルです。
「テレビ 4K」を検索エリアに入力して、検索後、タイトルを取得&コンソール出力しています。
セレクタとかは、セレクタにわかりやすく各言語の説明が書かれています。

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace SeleniumCSharp
{
    public partial class Main
    {
        public Main()
        {
            scriping();
        }

        [Obsolete]
        private void scriping()
        {
            IWebDriver driver = new ChromeDriver("C:\\webdriver");
            //Webページを開く
            driver.Navigate().GoToUrl("https://www.amazon.co.jp/");

            //検索ボックスに入力
            IWebElement searchtextbox = driver.FindElement(By.Id("twotabsearchtextbox"));
            searchtextbox.SendKeys("テレビ 4K");

            //検索実行
            IWebElement searchbtn = driver.FindElement(By.ClassName("nav-input"));
            searchbtn.Click();

            //画面の表示が終わるまで待機(最大10秒)
            TimeSpan TIMEOUT = new TimeSpan(0, 0, 10); // 10秒
            WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
            wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.CssSelector("span.a-size-base-plus")));
            //要素を探す(タイトル)
            IReadOnlyList<IWebElement> spans = driver.FindElements(By.CssSelector("span.a-size-base-plus"));
            //各要素を出力
            foreach (IWebElement span in spans)
            {
                //商品名を出力
                Console.WriteLine( span.Text);
            }
        }
    }
}
1
4
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
4