Last active
October 16, 2022 11:31
-
-
Save jayrgee/568435f7b22c4cb57224be01ed1cd0e1 to your computer and use it in GitHub Desktop.
Get Selected Option value with Selenium 4.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$url = "file:///C:/Users/jrg/code/powershell/ps-selenium/html/select.html" | |
$pathWebDriver = Join-Path $PSScriptRoot "WebDriver" | |
Import-Module (Join-path $pathWebDriver "WebDriver.dll") | |
Import-Module (Join-path $pathWebDriver "WebDriver.Support.dll") | |
$edgeOptions = New-Object OpenQA.Selenium.Edge.EdgeOptions | |
$edgeOptions.AddArgument("log-level=3") | |
$driver = New-Object OpenQA.Selenium.Edge.EdgeDriver($pathWebDriver, $edgeOptions) | |
Write-Host "Browsing to $url" | |
$driver.Navigate().GoToUrl($url) | |
# | |
# Handle disabled Select elements | |
# Use XPath to interrogate disabled Select Option value | |
# Cannot use Support.UI.SelectElement on disabled selects from Selenium 4.5!!! | |
# https://github.com/SeleniumHQ/selenium/commit/fa85effa0e77d946a3f4dcc94a9d0b6b407c2749 | |
# | |
function GetSelectValue2way ([OpenQA.Selenium.WebElement]$select) | |
{ | |
if ($select.TagName -ne "select") { return } | |
if ($select.Enabled) { | |
Write-Host "Select Enabled" -ForegroundColor Green | |
$selectElement = New-Object OpenQA.Selenium.Support.UI.SelectElement($select); | |
$text = $selectElement.SelectedOption.Text | |
} else { | |
Write-Host "Select Disabled" -ForegroundColor Red | |
$text = $select.FindElement([OpenQA.Selenium.By]::XPath("option[@selected]")).Text | |
} | |
return $text | |
} | |
function GetSelectedOption ([OpenQA.Selenium.WebElement]$select) | |
{ | |
if ($select.TagName -ne "select") { return $null } | |
$select.FindElement([OpenQA.Selenium.By]::XPath("option[@selected]")) | |
} | |
$pet = $driver.FindElement([OpenQA.Selenium.By]::Id("pet-select")) | |
Write-Host (GetSelectValue2way $pet) -ForegroundColor Green | |
Write-Host (GetSelectedOption $pet).Text -ForegroundColor Yellow | |
$colour = $driver.FindElement([OpenQA.Selenium.By]::Id("colour-select")) | |
Write-Host (GetSelectValue2way $colour) -ForegroundColor Red | |
Write-Host (GetSelectedOption $colour).Text -ForegroundColor Yellow | |
Start-Sleep -Seconds 5 | |
$driver.Close() | |
$driver.Quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment