PowerShell:测试网页中是否存在元素

时间:2017-10-07 03:00:08

标签: powershell ie-automation

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

$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为#34; admin"的元素 - 为什么并不重要。)

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

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

结果相同。

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

1 个答案:

答案 0 :(得分: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   

我建议您使用其中一个比较来确定“admin”是否确实存在:

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

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

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

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