Powershell: Use latest selenium version

Hi,

the selenium module from the powershell gallery outdated is outdated.

Here is my method to use the latest selenium nuget version for a script with Chrome.

First load requiered assemblies

PS D:\> [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")

Create a project directory

PS D:\> mkdir D:\MyProject
PS D:\> cd D:\MyProject
PS D:\> $PWD="D:\MyProject"

Define URLs for Selenium.WebDriver, Newtonsoft.Json,Chromedriver, Edgedriver and Firefox. URLs are the link to nuget packages which are zip conpressed files.

PS D:\MyProject> $sNewtonSoftURL='https://www.nuget.org/api/v2/package/Newtonsoft.Json' 
PS D:\MyProject> $sSeleniumWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver'
PS D:\MyProject> $sChromWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.ChromeDriver'
PS D:\MyProject> $sEdgeWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.MSEdgeDriver'
PS D:\MyProject> $sFireFoxWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.GeckoDriver'
PS D:\MyProject> $sNewtonSoftDLL=[System.IO.Path]::Combine($PWD,"Newtonsoft.Json.dll")
PS D:\MyProject> $sSeleniumWebdriverDLL=[System.IO.Path]::Combine($PWD,"WebDriver.dll")
PS D:\MyProject> $sChromeWebdriverEXE=[System.IO.Path]::Combine($PWD,"chromedriver.exe")
PS D:\MyProject> $sEdgeWebdriverEXE=[System.IO.Path]::Combine($PWD,"msedgedriver.exe")
PS D:\MyProject> $sFirefoxWebdriverEXE=[System.IO.Path]::Combine($PWD,"geckodriver.exe")

Download the files

PS D:\MyProject> $sTempNewtonSoftNUGETPackage=[System.IO.Path]::GetTempFileName()
PS D:\MyProject> Invoke-WebRequest -Uri $sNewtonSoftURL -OutFile $sTempNewtonSoftNUGETPackage
PS D:\MyProject> $sNewtonSoftNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempNewtonSoftNUGETPackage)
PS D:\MyProject> $sNewtonSoftNUGETPackage.Entries | ?{$_.FullName -eq "lib/net45/Newtonsoft.Json.dll" } | %{
    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sNewtonSoftDLL)
}
PS D:\MyProject> $sTempSeleniumWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
PS D:\MyProject> Invoke-WebRequest -Uri $sSeleniumWebdriverURL -OutFile $sTempSeleniumWebdriverNUGETPackage
PS D:\MyProject> $sSeleniumWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempSeleniumWebdriverNUGETPackage)
PS D:\MyProject> $sSeleniumWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "lib/netstandard2.0/WebDriver.dll" } | %{
    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sSeleniumWebdriverDLL)
}

PS D:\MyProject> $sTempChromeWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
PS D:\MyProject> Invoke-WebRequest -Uri $sChromWebdriverURL -OutFile $sTempChromeWebdriverNUGETPackage
PS D:\MyProject> $sChromeWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempChromeWebdriverNUGETPackage)
PS D:\MyProject> $sChromeWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "driver/win32/chromedriver.exe" } | %{
    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sChromeWebdriverEXE)
}

Download and load assembly and start the browser with 2 functions

function Load-Selenium
{
	<#
		.SYNOPSIS
        Loads the selenium libraries for a specific browser
		.DESCRIPTION
			Loads the selenium libraries for a specific browser. If the libraries not exists
			the function loads the latest version.
		.PARAMETER Download
			Force download of the latest version before loading	
	#>	
    param(
        [Parameter(mandatory=$false)][ValidateSet('Chrome','Edge','Firefox')][string]$ForBrowser,    
        [Parameter(mandatory=$false)][switch]$Download = $false
    )
	[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | out-null
	$sNewtonSoftURL='https://www.nuget.org/api/v2/package/Newtonsoft.Json'
	$sSeleniumWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver'
	$sChromWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.ChromeDriver'
	$sEdgeWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.MSEdgeDriver'
	$sFireFoxWebdriverURL='https://www.nuget.org/api/v2/package/Selenium.WebDriver.GeckoDriver'
	$sNewtonSoftDLL=[System.IO.Path]::Combine($PWD,"Newtonsoft.Json.dll")
	$sSeleniumWebdriverDLL=[System.IO.Path]::Combine($PWD,"WebDriver.dll")
	$sChromeWebdriverEXE=[System.IO.Path]::Combine($PWD,"chromedriver.exe")
	$sEdgeWebdriverEXE=[System.IO.Path]::Combine($PWD,"msedgedriver.exe")
	$sFirefoxWebdriverEXE=[System.IO.Path]::Combine($PWD,"geckodriver.exe")

	if(!(Test-Path $sNewtonSoftDLL) -or $Download)
	{
		if([appdomain]::currentdomain.GetAssemblies() | ?{$_.Location -eq $sNewtonSoftDLL})
		{
			write-host ("{0} is loaded and cannot be updated. Please close powershell window(s)" -f $sNewtonSoftDLL)
			return
		}
		$sTempNewtonSoftNUGETPackage=[System.IO.Path]::GetTempFileName()
		Invoke-WebRequest -Uri $sNewtonSoftURL -OutFile $sTempNewtonSoftNUGETPackage
		$sNewtonSoftNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempNewtonSoftNUGETPackage)
		$sNewtonSoftNUGETPackage.Entries | ?{$_.FullName -eq "lib/net45/Newtonsoft.Json.dll" } | %{
			[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sNewtonSoftDLL,$true)
		}
		$sNewtonSoftNUGETPackage.Dispose()
		Remove-item $sTempNewtonSoftNUGETPackage
	}
	Add-Type -Path $sNewtonSoftDLL -ErrorAction Stop
	if(!(Test-Path $sSeleniumWebdriverDLL) -or $Download)
	{
		if([appdomain]::currentdomain.GetAssemblies() | ?{$_.Location -eq $sSeleniumWebdriverDLL})
		{
			write-host ("{0} is loaded and cannot be updated. Please close powershell window(s)" -f $sSeleniumWebdriverDLL)
			return
		}		
		$sTempSeleniumWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
		Invoke-WebRequest -Uri $sSeleniumWebdriverURL -OutFile $sTempSeleniumWebdriverNUGETPackage
		$sSeleniumWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempSeleniumWebdriverNUGETPackage)
		$sSeleniumWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "lib/netstandard2.0/WebDriver.dll" } | %{
			[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sSeleniumWebdriverDLL,$true)
		}
		$sSeleniumWebdriverNUGETPackage.Dispose()
		Remove-item $sTempSeleniumWebdriverNUGETPackage
	}	
	Add-Type -Path $sSeleniumWebdriverDLL -ErrorAction Stop
	if($ForBrowser -eq "Chrome")
	{
		if(!(Test-Path $sChromeWebdriverEXE) -or $Download)
		{
			$sTempChromeWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
			Invoke-WebRequest -Uri $sChromWebdriverURL -OutFile $sTempChromeWebdriverNUGETPackage
			$sChromeWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempChromeWebdriverNUGETPackage)
			$sChromeWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "driver/win32/chromedriver.exe" } | %{
				[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sChromeWebdriverEXE,$true)
			}
			$sChromeWebdriverNUGETPackage.Dispose()
			Remove-item $sTempChromeWebdriverNUGETPackage
		}
	}	
	
	if($ForBrowser -eq "Edge")
	{
		if(!(Test-Path $sEdgeWebdriverEXE) -or $Download)
		{
			$sTempEdgeWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
			Invoke-WebRequest -Uri $sEdgeWebdriverURL -OutFile $sTempEdgeWebdriverNUGETPackage
			$sEdgeWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempEdgeWebdriverNUGETPackage)
			$sEdgeWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "driver/win32/msedgedriver.exe" } | %{
				[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sEdgeWebdriverEXE,$true)
			}
			$sEdgeWebdriverNUGETPackage.Dispose()
			Remove-item $sTempEdgeWebdriverNUGETPackage
		}	
	}
	if($ForBrowser -eq "Firefox")
	{
		if(!(Test-Path $sFirefoxWebdriverEXE) -or $Download)
		{
			$sTempFirefoxWebdriverNUGETPackage=[System.IO.Path]::GetTempFileName()
			Invoke-WebRequest -Uri $sFirefoxWebdriverURL -OutFile $sTempFirefoxWebdriverNUGETPackage
			$sFirefoxWebdriverNUGETPackage = [System.IO.Compression.ZipFile]::OpenRead($sTempFirefoxWebdriverNUGETPackage)
			$sFirefoxWebdriverNUGETPackage.Entries | ?{$_.FullName -eq "driver/win32/Firefoxdriver.exe" } | %{
				[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_,$sFirefoxWebdriverEXE,$true)
			}
			$sFirefoxWebdriverNUGETPackage.Dispose()
			Remove-item $sTempFirefoxWebdriverNUGETPackage
		}	
	}
}

function Start-Browser 
{
    param(
        [Parameter(mandatory=$true)][ValidateSet('Chrome','Edge','Firefox')][string]$browser   
	)	
	Load-Selenium -ForBrowser $browser
    switch($browser){
        'Chrome' {    
            $chrome = Get-Package -ErrorAction SilentlyContinue | ?{$_.Name -like "Google Chrome*" } | select -First 1    
            if (!$chrome){
                throw "Google Chrome Browser not installed."    
                return
            }
            # create driver service
            $oDriverService = [OpenQA.Selenium.Chrome.ChromeDriverService]::CreateDefaultService($PWD)
            # hide command prompt window
            $oDriverService.HideCommandPromptWindow = $true
            # create driver object
            $driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver $oDriverService 
        }
        'Edge' {    
            $edge = Get-Package -Name 'Microsoft Edge*' -ErrorAction SilentlyContinue | select -First 1    
            if (!$edge){
                throw "Microsoft Edge Browser not installed."    
                return
            }
            # create driver service
            $oDriverService = [OpenQA.Selenium.Edge.EdgeDriverService]::CreateDefaultService($PWD)
            # hide command prompt window
            $oDriverService.HideCommandPromptWindow = $true
            $driver = New-Object OpenQA.Selenium.Edge.EdgeDriver $oDriverService 
        }
        'Firefox' {    
            $ff = Get-Package -Name "Mozilla Firefox*" -ErrorAction SilentlyContinue | select -First 1        
            if (!$ff){
                throw "Mozilla Firefox Browser not installed."    
                return
            }
            # create driver service
            $oDriverService = [OpenQA.Selenium.Firefox.FirefoxDriverService]::CreateDefaultService($PWD)
            # hide command prompt window
            $oDriverService.HideCommandPromptWindow = $true
            # create driver object
            $driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver $oDriverService 
        }
    }
    return $driver
}

Some examples. Load the functions (i.e. copy & paste to the powershell window) then

PS D:\> mkdir MySeleniumProject
PS D:\> cd D:\MySeleniumProject
PS D:\MySeleniumProject> $WebDriver = Start-Browser Chrome
PS D:\MySeleniumProject> $WebDriver.Url = "https://www.ebay.de"

Page reload

$WebDriver.navigate().refresh()

Get EBay price

$WebDriver.FindElements([OpenQA.Selenium.By]::ClassName("x-price-primary")).FindElements([OpenQA.Selenium.By]::TagName("span")).Text

Bit button

$WebDriver.FindElements([OpenQA.Selenium.By]::XPath("//button[@data-elementid='MaxBidId']"))
$WebDriver.FindElements([OpenQA.Selenium.By]::XPath("//button[@data-elementid='MaxBidId']")).Click()

Get price input span element

$WebDriver.FindElements([OpenQA.Selenium.By]::XPath("//span[contains(@class,'textbox app-input-price__input textbox__empty')]"))

Get the input tag (child of span)

$InputTag=($WebDriver.FindElements([OpenQA.Selenium.By]::XPath("//span[contains(@class,'textbox app-input-price__input textbox__empty')]"))).findelements([OpenQA.Selenium.By]::TagName("input"))

Send backspaces to delete input

for($i=12;$i -ge 0;$i--)
{
$InputTag.SendKeys([OpenQA.Selenium.Keys]::Backspace)
}

Send price

$InputTag.SendKeys("10,00")
Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.