【发布时间】:2019-08-27 15:53:05
【问题描述】:
我需要填写内部网站的表格。我能够使用此代码成功登录到门户页面
$ie = New-Object -Com InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate("https://some-internal-ip/login")
while ($ie.ReadyState -ne 4) {Start-Sleep -m 100};
#Login
$form = $ie.document.forms[0]
$inputs = $form.GetElementsByTagName("input")
($inputs | where {$_.Name -eq "username"}).Value = $username
($inputs | where {$_.Name -eq "password"}).Value = $password
($inputs | where {$_.Name -eq "action:Login"}).Click()
#after login - navigate to this link
while ($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}
Start-Sleep -m 2000
$ie.Navigate("https://some-internal-ip/monitor/users")
以上工作正常。它将引导我进入我需要填写另一个表格的新链接。所以我重用了上面的代码来填写用户字段和提交按钮的表单。
此页面中有多个表单,因此我想将其缩小到这个特定的id="trackingSearchForm"。
HTML 表单:
<form action="https://.../" method="POST" name="trackingSearchForm" id="trackingSearchForm" accept-charset="utf-8" onsubmit="return false;">
<input name="user" onkeypress="keyPressHandler(this.form, event)" class="" type="text" id="user" value=">
<input type="button" class="submit" id="submitButton" value="Search" onclick="performSearch();">
获取表单ID并填写
while ($ie.ReadyState -ne 4 -or $ie.Busy) {Start-Sleep -m 100}
$form = $ie.Document.Forms[0]
$form = ($ie.Document.Forms[0] | where {$_.Id -eq "trackingSearchForm"})
$inputs = $form.GetElementsByTagName("input")
($inputs | where {$_.name -eq "user"}).Value = "john"
($inputs | where {$_.Id -eq "submitButton"}).Click()
但我收到以下错误:
您不能在空值表达式上调用方法。 + $inputs = $form.GetElementsByTagName("输入") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull 在此对象上找不到属性“值”。验证该属性 存在并且可以设置。 + ($inputs | where {$_.Name -eq "user"}).Value = "john" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId:PropertyNotFound我用于登录表单的相同代码不适用于其他表单。
【问题讨论】:
-
错误的意思是,
$form是空的。 -
制作
$ie.visible=$false,一步一步执行操作,看看发生了什么。 -
$ie.Document.Forms[0]是文档中的第一个<form>元素。如果该元素没有 ID "trackingSearchForm"$form将为空,从而导致您观察到的错误。如果您想要一个具有特定 ID 的元素,为什么不使用$ie.Document.GetElementById("trackingSearchForm")?
标签: powershell