使用 PowerShell 和 Selenium 4 等待元素

Sta*_*Guy 2 powershell selenium4

我正在更新一些以前与 Selenium 3.141 一起使用的 PowerShell 代码。我有以下代码片段:

Add-Type -LiteralPath "$seleniumPath\lib\net48\WebDriver.dll"
Add-Type -LiteralPath "$seleniumPath\lib\net48\WebDriver.Support.dll"
$url = "https://<webpage.com>"
$options = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$options.AddArgument("--disable-gpu")
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($options)
[OpenQA.Selenium.Support.UI.WebDriverWait]$wait = New-Object OpenQA.Selenium.Support.UI.WebDriverWait ($driver, [System.TimeSpan]::FromSeconds(60))

$driver.Navigate().GoToURL($url)
$driver.FindElementById("username")
$wait.Until([OpenQA.Selenium.Support.UI.ExpectedConditions]::ElementExists([OpenQA.Selenium.By]::Id('username')))
Run Code Online (Sandbox Code Playgroud)

在 Selenium 4.0 中,FindElementById 不再起作用:

无法找到类型 [OpenQA.Selenium.Support.UI.ExpectedConditions]。

据我所知,OpenQA.Selenium.Support.UI.ExpectedConditions 存在于 WebDriver.Support 中,对吧?

寻找替代品,我发现了 SeleniumExtras.WaitHelpers,但这可能只适用于 .netstandard2.1?

Sta*_*Guy 5

最后,这对我有用:

Add-Type -LiteralPath "$seleniumPath\lib\net48\WebDriver.dll"
Add-Type -LiteralPath "$seleniumPath\lib\net48\WebDriver.Support.dll"
$url = "https://<webpage.com>"
$options = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$options.AddArgument("--disable-gpu")
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($options)
[OpenQA.Selenium.Support.UI.WebDriverWait]$wait = New-Object OpenQA.Selenium.Support.UI.WebDriverWait ($driver, [System.TimeSpan]::FromSeconds(60))

$driver.Navigate().GoToURL($url)
$driver.FindElementById("username")

$wait.Until([System.Func[OpenQA.Selenium.IWebDriver, System.Boolean]] { param($driver) Try { $driver.FindElement([OpenQA.Selenium.By]::Id('username')) } Catch { $null } })
Run Code Online (Sandbox Code Playgroud)

如果您想返回元素对象而不是布尔值,只需将“System.Boolean”(最后一行)更改为“OpenQA.Selenium.IWebElement”即可。