LoginSignup
0
3

More than 1 year has passed since last update.

C# Seleniumで要素取得 --メモ--

Last updated at Posted at 2021-07-07

Visual Studio 2019 Communityを使用
NuGetでWebDriver chromedriver firefoxdriverなどを適宜インストール

※ 例外処理はしていません。

Seleniumにおける要素の取得

ロケーターの種類は8種類

ロケータ 詳細
class name class名に値を含む要素を探す (複合クラス名は使えない)
css selector CSSセレクタが一致する要素を探す
id id属性が一致する要素を探す
name name属性が一致する要素を探す
link text a要素のテキストが一致する要素を探す
partial link text a要素のテキストが部分一致する要素を探す
tag name タグ名が一致する要素を探す
xpath XPathと一致する要素を探す

FindElementsByClassNameでクラスを指定

using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {

            ChromeDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            driver.Navigate().GoToUrl(@"目的のURL");
            ReadOnlyCollection<IWebElement> itemList = driver.FindElementsByClassName("クラス名");

            foreach (IWebElement elm in itemList)
            {
                string str = elm.Text;
                Console.WriteLine(str);
            }


            Console.ReadKey();
            driver.Quit();
        }
    }
}

XPathでIDを指定

ここではFirefoxDriverを使った。

Firefoxなどの開発ツールでXPathをコピーするが、//*[@id="ID名"]のようにダブルクオートが含まれる。
これはC#ではエスケープする必要があるが、ここではシングルクオートで置換した。
XPathをコピーしたあと、次のPowerShellを実行。クリップボードに 置換後の文字列が格納される。

 (Get-Clipboard) -replace "`"" , "'" | Set-Clipboard
          IWebDriver driver = new FirefoxDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            driver.Navigate().GoToUrl(@"https://member.livedoor.com/login/");
            driver.Manage().Window.Maximize();

            driver.FindElement(By.XPath(@"//*[@id='livedoor_id']")).SendKeys(@"LivedoorブログID");
            driver.FindElement(By.XPath(@"//*[@id='password']")).SendKeys(@"Livedoorブログパス");
            driver.FindElement(By.XPath(@"//*[@id='check_auto_login']")).Click();
            driver.FindElement(By.XPath(@"//*[@id='submit']")).Click();
            driver.Navigate().GoToUrl(@"http://www.livedoor.com/");
            Console.ReadKey();
            driver.Quit();

CssSelectorでクラス指定

FindElement と FindElements で単数,複数の違いがあるようです。


using System;
using System.IO;
using System.Collections.ObjectModel;
using System.Reflection;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            IWebDriver driver = new FirefoxDriver(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            driver.Navigate().GoToUrl(@"https://www.w3schools.com/css/css_selectors.asp");

            //FindElementで単数形

            IWebElement elm = driver.FindElement(By.CssSelector(".w3-example"));
            Console.WriteLine(elm.Text);
            Console.WriteLine("■■■■■■■■■■■■■■■■■■■\n\n");

            //FindElement"s"  で複数形
            ReadOnlyCollection<IWebElement>  itemList= driver.FindElements(By.CssSelector(".w3-example"));
            foreach (IWebElement i in itemList)
            {
                Console.WriteLine(i.Text);
            }

            Console.ReadKey();
            driver.Quit();
        }
    }
}


[参考にした記事]
C#:SeleniumでWeb解析
Seleniumドキュメント 要素を探す
Seleniumで要素を選択する方法まとめ

0
3
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
0
3