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

PowerShell: Testing whether an element exists in web page

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

$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 行中的测试似乎无法正常工作:无论元素是否存在,它总是 returns TRUE。我也试过

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

结果相同。

我正在开发 Windows 10 系统。有什么想法吗?

问题出在你的比较上。命令 Document.getElementById 是 returning 与 DBNull 本身不等于 Null。因此,当你执行:

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

你总是 return 用 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

如果比较 return 与 True 则表示该值为 Empty,因此 "admin" 不存在。当然你可以使用 -ne 更方便。