0

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

$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 系统。有任何想法吗?

4

1 回答 1

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更方便。

于 2017-10-07T08:59:36.803 回答