Can powershell wait until IE is DOM ready?

前端 未结 2 659
梦毁少年i
梦毁少年i 2020-12-16 22:42

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

2条回答
  •  情深已故
    2020-12-16 23:20

    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"
    

提交回复
热议问题