Search code examples
powershellseleniumpowershell-5.1selenium4

Finding elements with PowerShell and Selenium 4


I am working on updating some PowerShell code that previously worked with Selenium 3.141. I have the following code snippet:

$url = "https://<webpage.com>"
$options = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$options.AddArgument("--disable-gpu")
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($options)
$driver.Navigate().GoToURL($url)
$driver.FindElementById("username")

With Selenium 4.0, FindElementById no longer works:

Method invocation failed because [OpenQA.Selenium.Chrome.ChromeDriver] does not contain a method named 'FindElementById'

Looking at https://www.lambdatest.com/blog/what-is-deprecated-in-selenium4/, I see that this ought to work (in Java):

driver.findElement(By.id("username"))

But I do not know how to translate that to PowerShell ($driver.FindElement(By.id("username")) does not work).

Any idea how I can find an element by ID (or class, xpath, etc.) with PowerShell and Selenium 4?


Solution

  • Specify the fully qualified class name of By:

    $driver.FindElement([OpenQA.Selenium.By]::Id("username"))
    

    The :: accessor is used because the Id() method is a static member of the By class.