Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

internet explorer - Can powershell wait until IE is DOM ready?

I'm currently writing a script and I'm using

while($IE.busy) {Start-Sleep 1}

to wait for the page to be ready.

Once the page is ready my script fills out and submits a form. I've been running into problems because (I think) IE reports that it's done when the page is loaded but before the document has been rendered (which causes the script to error out). My current workaround is to add a 4 second wait time after the page loads but I'd feel more comfortable with a method that isn't time based if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's how I do this.

Step 1 - Identify a web page element that only appears once the page is fully rendered. I did this using the Chrome developer tools 'Elements' view which shows the DOM view.

Step 2 - Establish a wait loop in the script which polls for the existence of the element or the value of text inside that element.

# Element ID to check for in DOM
$elementID = "systemmessage"

# Text to match in elemend
$elementMatchText = "logged in"

# Timeout
$timeoutMilliseconds = 5000

$ie = New-Object -ComObject "InternetExplorer.Application"

# optional
$ie.Visible = $true

$ie.Navigate2("http://somewebpage")
$timeStart = Get-Date
$exitFlag = $false

do {

    sleep -milliseconds 100

    if ( $ie.ReadyState -eq 4 ) {

        $elementText = (($ie.Document).getElementByID($elementID )).innerText
        $elementMatch = $elementText -match $elementMatchText

        if ( $elementMatch ) { $loadTime = (Get-Date).subtract($timeStart) }

    }

    $timeout = ((Get-Date).subtract($timeStart)).TotalMilliseconds -gt $timeoutMilliseconds
    $exitFlag = $elementMatch -or $timeout

} until ( $exitFlag )

Write-Host "Match element found: $elementMatch"
Write-Host "Timeout: $timeout"
Write-Host "Load Time: $loadTime"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...