Dom 用于执行web UI自动化的Powershell脚本不起作用

Dom 用于执行web UI自动化的Powershell脚本不起作用,dom,powershell,ui-automation,Dom,Powershell,Ui Automation,我有这个脚本来启动IE,导航到一个页面并搜索一些文本: $ie = new-object -com "InternetExplorer.Application" $ie.Visible = $true $ie.Navigate("http://www.google.com") $doc = $ie.Document if ($doc -eq $null) { Write-Host "The document is null." return } $tb1 = $doc.getEl

我有这个脚本来启动IE,导航到一个页面并搜索一些文本:

$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$ie.Navigate("http://www.google.com")
$doc = $ie.Document
if ($doc -eq $null)
{
    Write-Host "The document is null."
    return
}
$tb1 = $doc.getElementsByName("q") # a text box
$tb1.value = "search text";
$btn = $doc.getElementsByName("btnG")
$btn.click()
我将其保存为ps1文件,并从命令行运行它。。。但是$ie.document返回的文档对象始终为空

我做错了什么

另外,当我在解释器模式下逐行运行脚本时,会返回文档,但下一行$tb=$doc.getElementsByNameq错误:在该对象上找不到属性“Value”;确保它存在并且可设置


那么,如何设置文本框的值?

您需要检查IE是否在$doc分配之前加载了页面。比如说,

while ($ie.busy) {
#Sleep a bit
}
我尝试了同样的代码来输入搜索文本和点击按钮,但没有成功。因此,最终将您的代码修改为

$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$ie.Navigate("http://www.google.com")
While ($ie.Busy) {
Sleep 2
}
$doc = $ie.Document

$btns = $doc.getElementsByTagName("input")
$SearchText = $btns | ? { $_.Name -eq "q" }
$SearchText.value = "search text"
$SearchButton = $btns | ? { $_.Name -eq "btnG" }
$SearchButton.click()

您需要检查IE是否在$doc分配之前加载页面。比如说,

while ($ie.busy) {
#Sleep a bit
}
我尝试了同样的代码来输入搜索文本和点击按钮,但没有成功。因此,最终将您的代码修改为

$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$ie.Navigate("http://www.google.com")
While ($ie.Busy) {
Sleep 2
}
$doc = $ie.Document

$btns = $doc.getElementsByTagName("input")
$SearchText = $btns | ? { $_.Name -eq "q" }
$SearchText.value = "search text"
$SearchButton = $btns | ? { $_.Name -eq "btnG" }
$SearchButton.click()

我相信我可以看到两个问题。首先,Ravikath建议添加等待页面完成加载的功能,这一点很重要。如果不等待页面加载,即$ie.busy-eq$false,则无法获取完整文档

第二,不管出于什么原因,谷歌决定添加多个输入字段,名称为q。您可以向Ravikanth的查询添加第二个条件,如下所述:

$SearchText = $btns | ? { $_.Name -eq "q" -and $_.Type -eq "text"}

我相信我可以看到两个问题。首先,Ravikath建议添加等待页面完成加载的功能,这一点很重要。如果不等待页面加载,即$ie.busy-eq$false,则无法获取完整文档

第二,不管出于什么原因,谷歌决定添加多个输入字段,名称为q。您可以向Ravikanth的查询添加第二个条件,如下所述:

$SearchText = $btns | ? { $_.Name -eq "q" -and $_.Type -eq "text"}

拉维坎特,谢谢-你的修复成功了。但是为什么我使用$doc.getElementsByNameq时它不起作用?使用它有什么问题吗?不确定。它有几个属性。可能需要再看一次。拉维坎特,谢谢-你的修复成功了。但是为什么我使用$doc.getElementsByNameq时它不起作用?使用它有什么问题吗?不确定。它有几个属性。可能需要再看一次。