LoginSignup
5
10

More than 3 years have passed since last update.

PowerShellでSelenium WebDriverを使うための勘所

Last updated at Posted at 2020-04-05

はじめに

PowerShellからSeleniumを使ってみてインストールから使いたい機能の調べ方まで分かったことをまとめます。

始める

初めて使うならこのサイトがおすすめです。

このサイトではSeleniumのライブラリを直接ダウンロードしていますがnugetを使うとコマンドのみで完結するので楽です。

ライブラリのダウンロード

nuget install Selenium.WebDriver
nuget install Selenium.Support
nuget install Selenium.WebDriver.ChromeDriver

初期化とchrome起動と終了

フォルダ名のバージョンはダウンロードしたものを合わせてください。

# パス設定
## nugetでダウンロードしたフォルダ
$seleniumHome = '.'
## WebDriver.dllのフルパス
$webDriverDllPath        = Convert-Path (Join-Path $seleniumHome '\Selenium.WebDriver.3.141.0\lib\netstandard2.0\WebDriver.dll')
## WebDriver.Support.dllのフルパス
$webDriverSupportDllPath = Convert-Path (Join-Path $seleniumHome '\Selenium.Support.3.141.0\lib\netstandard2.0\WebDriver.Support.dll')
## chromedriver.exeがあるフォルダのパス
$chromeDriverDirPath     = Convert-Path (Join-Path $seleniumHome '\Selenium.WebDriver.ChromeDriver.80.0.3987.10600\driver\win32')

# dll読み込み
Add-Type -Path $webDriverDllPath
Add-Type -Path $webDriverSupportDllPath

# chrome起動
$chromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($chromeDriverDirPath)

# chrome終了
$chromeDriver.Quit()

雰囲気が分かってきたら

Seleniumの公式ドキュメントを辿ると機能とそのためのサンプルコードが載っているので参考になります。

特によく使いそうな機能も解説されています。

Selenium PowerShell Module

できる事が分かってくるとPowerShell Moduleを使ってもいいでしょう。これは全部入りなので個別にdllをダウンロードしなくても利用できます。

モジュールのインストール

Install-Module -Scope CurrentUser Selenium

サンプルは以下のフォルダに用意されています。

このモジュールでchrome起動と終了は以下のようになります。

# Seleniumモジュールをインポート
try {
    Import-Module -Name Selenium -ErrorAction Stop
}
catch {
    Write-Host 'Importing the Selenium module failed. Please install it using the following command: Install-Module Selenium'
    break
}

# chrome起動
$Driver = Start-SeChrome

if (!$Driver) {
    Write-Host "The selenium driver was not running." -ForegroundColor Yellow
    Return
}

# chrome終了
Stop-SeDriver -Driver $Driver

もっと詳しく

使いたいクラスのnamespaceやメソッドを探すときはAPIリファレンスから探すといいでしょう。

5
10
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
5
10