Selenium - Powershell - 等待元素不起作用

问题描述 投票:0回答:1

我正在尝试延长元素的等待时间。然而,似乎增加的超时 60 秒和默认的 10 秒都没有被识别。网站加载大约需要一秒半的时间,但我立即收到一条错误消息,指出无法找到我要查找的第一个元素。

cls
$workingPath = "D:\Dev\Selenium"
$env:PATH += ";$workingPath"
Add-Type -Path "$($workingPath)\lib\netstandard2.0\WebDriver.dll"
Add-Type -Path "$($workingPath)\lib\netstandard2.0\WebDriver.Support.dll"

$chromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions
$chromeOptions.AddArgument('start-maximized')
$chromeOptions.AddArgument('disable-gpu')
$chromeOptions.AddArgument('ignore-certificate-errors')
$chromeDriver = New-Object OpenQA.Selenium.Chrome.ChromeDriver($workingPath, $chromeOptions)

[OpenQA.Selenium.Support.UI.WebDriverWait]$wait = New-Object OpenQA.Selenium.Support.UI.WebDriverWait ($chromeDriver, [System.TimeSpan]::FromSeconds(60))

$SiteUrl = "http://192.168.27.10"
$chromeDriver.Navigate().GoToURL($siteURL)

$username = $ChromeDriver.FindElement([OpenQA.Selenium.By]::Id('loginUsername-inputEl'))
$wait.Until([System.Func[OpenQA.Selenium.IWebDriver, OpenQA.Selenium.IWebElement]] { param($chromeDriver)Try { $username } Catch { $null } })

据我所知,上述“应该”有效。然而,一旦网站加载,似乎没有任何等待元素,并抛出以下错误:

Exception calling "FindElement" with "1" argument(s): "no such element: Unable to locate element: {"method":"css selector","selector":"#loginUsername\-inputEl"}
  (Session info: chrome=123.0.6312.123); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception"
At line:18 char:1
+ $username = $ChromeDriver.FindElement([OpenQA.Selenium.By]::Id('login ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NoSuchElementException

我可以通过运行 $wait 确认等待确实调整为 60 秒:

$wait

Timeout  PollingInterval  Message
-------  ---------------  -------
00:01:00 00:00:00.5000000 

也许我做错了什么;我不知道。有什么建议吗??

powershell selenium-webdriver selenium-chromedriver
1个回答
0
投票

您当前的代码没有多大意义。您正在等待

FindElement()
调用的第一个结果,而不是重复调用
FindElement()

我认为

FindElement
调用应该位于
$wait.Until()
调用的脚本块内:

$script:username = $null

$wait.Until( [System.Func[OpenQA.Selenium.IWebDriver, OpenQA.Selenium.IWebElement]] { param($chromeDriver)

    try {
        $script:username = $chromeDriver.FindElement([OpenQA.Selenium.By]::Id('loginUsername-inputEl'))
        $true  # As there was no exception, exit the wait loop
    }
    Catch { 
        $false  # Exception occurred, need to wait another time
    } 
})

# For debugging, output the value of the variable after the wait loop has finished
$script:username

注:

  • 我使用脚本范围的变量,因为
    $wait.Until()
    调用的脚本块在新范围中运行,无法直接访问父范围中的变量。还有其他选项,例如使用参考或使用
    Set-Variable -Scope 1
    ,您可能想要探索
© www.soinside.com 2019 - 2024. All rights reserved.