【问题标题】:PowerShell: Testing whether an element exists in web pagePowerShell:测试网页中是否存在元素
【发布时间】:2017-10-07 03:00:07
【问题描述】:

我正在尝试查找网页中是否存在元素:

$ie = New-Object -com InternetExplorer.Application
$ie.visible = $true
$ie.Navigate("http://10.0.0.1")
BrowserReady($ie) # wait for page to finish loading
if ($ie.Document.getElementById("admin")) {
  $ie.Document.getElementById("admin").value = "adminuser"
}
etc, etc

(是的,http://10.0.0.1 处的页面可能不包含 id 为“admin”的元素 - 为什么不重要。)

我的问题是第 5 行的测试似乎无法正常工作:无论元素是否存在,它总是返回 TRUE。我也试过了

if ($ie.Document.getElementById("admin") -ne $NULL) {...}

结果相同。

我正在使用 Windows 10 系统。有什么想法吗?

【问题讨论】:

  • 因此在if 语句中进行测试
  • 天啊!我正在阅读它,但认为它正在测试“不存在”

标签: powershell ie-automation


【解决方案1】:

问题在于你的比较。命令Document.getElementById 返回DBNull,它本身不等于Null。因此,当你执行时:

if ($ie.Document.getElementById("admin"))
{
   ...
}

您总是返回True。如下例所示,$my_element 不等于$null,其类型为DBNull

PS > $my_element = $ie.Document.getElementById("admin")

PS > $my_element -eq $null
False

PS > $my_element.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                     
-------- -------- ----                                     --------   
True     True     DBNull                                   System.Object   

我建议您使用以下比较之一来确定“管理员”是否真的存在:

PS > $my_element.ToString() -eq ""
True

PS > [String]::IsNullOrEmpty($my_element.ToString())
True

PS > $my_element.ToString() -eq [String]::Empty
True

如果比较返回True,则表示该值为,因此“admin”不存在。当然,您可以使用-ne 来获得更多便利。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-11
    • 2021-03-04
    • 2022-01-14
    • 1970-01-01
    • 2011-12-04
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多