使用 PowerShell 和 Selenium 4 等待元素

Waiting for elements with PowerShell and Selenium 4

我正在更新一些以前使用 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')))

对于 Selenium 4.0,FindElementById 不再有效:

Unable to find type [OpenQA.Selenium.Support.UI.ExpectedConditions].

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

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

最后,这对我有用:

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 } })

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

ExpectedConditions class 已根据 .Net changelog:

弃用和删除

v3.11.0

Marked .NET ExpectedConditions obsolete. Using the ExpectedConditions class provides no benefit over directly using lambda functions (anonymous methods) directly in one's code. Since the community appears to believe that an "official" repository of wait conditions is desireable, the existing code has been migrated to a new repository under a new organization on GitHub. It is hoped that this will encourage a volunteer from the community to take ownership of this code. Users should update their references and migrate their code to use SeleniumExtras.ExpectedConditions. This implementation will be removed from the .NET language bindings in a future release

v4.0.0a1

Removed deprecated ExpectedConditions and PageFactory classes, as well as the supporting classes thereof.

正如@StackExchangeGuy 指出的那样,在 Powershell 中使用脚本块类似于 C# 中的 lamba 表达式。要继续使用 ExpectedConditions class,您可以 a) 从源构建 DotNetSeleniumExtras 并导入它或 b) 降级到 v3.141.0.