【问题标题】:PowerShell fill up form and submitPowerShell 填写表格并提交
【发布时间】: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] 是文档中的第一个 &lt;form&gt; 元素。如果该元素没有 ID "trackingSearchForm" $form 将为空,从而导致您观察到的错误。如果您想要一个具有特定 ID 的元素,为什么不使用 $ie.Document.GetElementById("trackingSearchForm")

标签: powershell


【解决方案1】:

错误大概在这一行:

$form = ($ie.document.forms[0] | where {$_.id -eq "trackingSearchForm"})

删除$forms的索引:

$form = ($ie.document.forms | where {$_.id -eq "trackingSearchForm"})

【讨论】:

  • 错过了这个我觉得很愚蠢!谢谢!后续问题。如果我在同一页面中有多个表格,我是否只需遍历索引号,例如 forms[1] 来指定我要填写的表格?
  • 别傻了,当你盯着脚本看太久时会发生这种情况 ;-) 如果可能的话,我总是用它们的 id 来引用表单(就像你在你的代码)。使用数字索引是可能的,但当 HTML 源代码在未来发生变化时更有可能削弱您的代码。
  • PS:也许你可以循环遍历所有表单,将它们存储在哈希表中,然后以这种(未经测试)的方式通过它们的 id(而不是索引)引用它们:$forms = @{}; $ie.document.forms | % { $forms[$_.id] = $_ } -- > 这应该允许您在脚本中使用$forms["trackingSearchForm"]
猜你喜欢
  • 2018-08-16
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多