开发者

Powershell script to do web UI Automation not working

开发者 https://www.devze.com 2023-01-30 19:34 出处:网络
I have this script to launch IE, navigate to a page and search for some text: $ie = new-object -com \"InternetExplorer.Application\"

I have this script to launch IE, navigate to a page and search for some text:

$ie = new-object -com "InternetExplorer.Application"
$ie.Visible = $true
$i开发者_StackOverflowe.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()

I save this as a ps1 file and run it from the command line... but the document object returned by $ie.Document is always null.

What am I doing wrong?

Also, when I run the script line by line in interpreter mode, the document is returned, but the next line $tb = $doc.getElementsByName("q") errors with this: Property 'Value' cannot be found on this object; make sure it exists and is settable.

How do I set the value of the text box, then?


You need to check if IE was done loading the page before $doc assignment. For example,

while ($ie.busy) {
#Sleep a bit
}

I tried the same code for entering the search text and button click but that did not work. So, ended up modiying your code to

$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()


I believe there are two issues that I can see. First, Ravikahth's suggestion to add the ability to wait for the page to finish loading is important. If you do not wait for the page to load (i.e. $ie.busy -eq $false), then you will not get the full document.

Second, for whatever reason, Google decided to add multiple input fields with the name of "q." You can add a second condition to Ravikanth's query as stated below:

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

精彩评论

暂无评论...
验证码 换一张
取 消