Jump to content

While Loop confusion


AJB
 Share

Recommended Posts

Hello,

I am relatively new to autoit (and this type of programming in general, typically do front end web dev). I have been tasked with writing some scripts to login to, navigate, and download files from some private websites. I have been hacking my way through these projects with plenty of wrong turns, cursing, and confusion.

 

I currently have a script that works, but utilizes some rather lengthy Sleep times to manage varying page loading times. During page loads, there will often be text that says "Page Loading" I am trying to write some code to check whether this exists after particular steps, then if it does sleep for a few seconds, then check again until it no longer exists (page has loaded) then proceed. This is what I was trying based on sample code that I've seen throughout my google searches. It doesn't seem to work correctly, can someone point out what I'm doing wrong, or provide links to a 'for dummies' explanation of how to do what I'm trying to do?

$body = _IEBodyReadHTML($oIE)
 While
   If StringInStr($body, "Page Loading")== 1 Then
      Sleep(5000)
   Else
   EndIf
WEnd

Thank you for your insight.

Link to comment
Share on other sites

Func _IE_Wait_notCpuMemoryChanges(ByRef $oIE, $iSleep = 0)
    If IsObj($oIE) Then
        Local $iIEPID = _IE_GetPid($oIE)
        Local Static $iWorkingSetSize
        Local Static $iPeakWorkingSetSize
        Local $aMemory
        While 1
            $aMemory = ProcessGetStats($iIEPID)
            If UBound($aMemory) Then
                If $iWorkingSetSize <> $aMemory[0] Or $iPeakWorkingSetSize <> $aMemory[1] Then
                    $iWorkingSetSize = $aMemory[0]
                    $iPeakWorkingSetSize = $aMemory[1]
                    If $iSleep <> 0 Then Sleep($iSleep)
                Else
                    ExitLoop
                EndIf
            Else
                ExitLoop
            EndIf
        WEnd
    EndIf
EndFunc   ;==>_IE_Wait_notCpuMemoryChanges

Func _IE_GetPid(ByRef $oIE)
;~  http://www.autoitscript.com/forum/topic/152691-how-to-know-pid-in-this-case/#entry1096901
    Local $hwnd = _IEPropertyGet($oIE, 'hwnd')
    Local $PID = DllStructCreate("int")
    Local $aCall = DllCall("user32.dll", "int", "GetWindowThreadProcessId", "hwnd", HWnd($hwnd), "dword*", DllStructGetPtr($PID))
    Return $aCall[2]
;~     MsgBox(0,"PID", $aCall[2])
EndFunc   ;==>_IE_GetPid

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

For the concept  ;)

While 1
   $body = _IEBodyReadHTML($oIE)
   If StringInStr($body, "Page Loading") Then
      Sleep(5000)
   Else
      Exitloop
   EndIf
WEnd

 

I see that I neglected to include the Exitloop per your sample, but when trying to implement it I've ended up with an infinite loop, even though the "Page Loading" string is no longer in $body. I'm wondering if it relates to another issue that I was having, where my _IE commands were referencing the previous instance of html after each page change (I've been working around this by reattaching to the page with $oIE = _IEAttach after every link followed, page change, etc. to get the current iteration of the page). Or am I just not getting the concept?

Thank you for your help.

Link to comment
Share on other sites

Including Exitloop is necessary but not sufficient, you must also put the _IEBodyReadHTML inside the loop so you do every time the StringInStr checking on a refreshed source content

Is the example format incorrect then? I assumed that everything within the While and WEnd was within the loop. I also tried putting some gibberish as the string in the If statement (assuming that since it wouldn't be anywhere in $body that it would exit immediately)but it still just does infinite loops without ever exiting. 

Link to comment
Share on other sites

Is the example format incorrect then? I assumed that everything within the While and WEnd was within the loop. I also tried putting some gibberish as the string in the If statement (assuming that since it wouldn't be anywhere in $body that it would exit immediately)but it still just does infinite loops without ever exiting. 

If it never exits, then you have a problem with your $oIE.

Link to comment
Share on other sites

#include <IE.au3>
#include <Date.au3>
#include <Excel.au3>
#include <MsgBoxConstants.au3>

Call ("myFunc")

Func myFunc()

;This deletes the file if it still exists
IF FileExists("C:\filenameexample.csv") == 1 Then
    FileDelete("C:\filenameexample.csv")
EndIf

$oIE = _IECreate ("http://www.example.com/login")

$username = _IEGetObjById ($oIE, "login_username")
$password = _IEGetObjById ($oIE, "login_password")

;Fill in login credentials and submit
_IEFormElementSetValue ($username, "exampleusername")
_IEFormElementSetValue ($password, "examplepassword")
$oButtons = _IETagNameGetCollection ($oIE, "button")
 For $oButton In $oButtons
    If $oButton.type = "submit" Then _IEAction ($oButton, "click")
 Next
Sleep(15000)

;Reattach to page - I HAVE TO DO THIS EVERY SINGLE TIME
$oIE = _IEAttach("welcome KEVIN","text")

;Select the lead type from dropdown
$LeadType = _IEGetObjByName($oIE, "data[leads_types]")
$LeadType.focus
_IEFormElementOptionSelect($LeadType, "Expired", 1, "byText")
Sleep(2000)

;click Filter button
$filterBtn = _IEGetObjById($oIE, "advanced_search")
_IEAction($filterBtn, "click")
Sleep(5000)

;Check for page load
$oIE = _IEAttach("welcome KEVIN","text")
; trying to attach again
While 1
  $body = _IEBodyReadHTML($oIE)
  If StringInStr($body, "Page Loading") Then ;I can put anything as that string but it loops infinitely anyway
      Sleep(5000)
      MsgBox($MB_SYSTEMMODAL, "Loop", "Looping", 1)
   Else
      Exitloop
   EndIf
WEnd

continues................

This is the code that leads up to the looping issue. The other issue is the attachment problem, every time I do anything creates a change on the page, follow a link, press a button, etc autoit needs to be reattached. I'm fairly certain this is causing the loop problem because it isn't seeing the new "Page loading" div. Is this normal behavior for autoit and the IE udf? 

This is also creating an issue later in my code where I open and paste into an excel sheet and save. When I reactivate the IE window I can't even attach to it... 

Thanks again to everyone for taking their time to reply and help me work through this.

Link to comment
Share on other sites

I know this has nothing to do with the issues you are trying to resolve, but with my admittedly limited coding skills, I offer this, only because I believe the shorter the code, the more elegant it is.  Much of your code is over my head, simply because I haven't worked much with IE.au3 functions.  However, AutoIt has a wonderful feature which allows you to eliminate some overhead when creating some If...EndIf statements.  The first task in your function cold be written as follows, on one line, no EndIf required:

Func myFunc()

;This deletes the file if it still exists
IF FileExists "C:\filenameexample.csv" Then  FileDelete("C:\filenameexample.csv")

 

Sorry, I don't seem to see the "insert code" button, but the code I suggest is so short as to almost eliminate the need for it.

I hope you are as delighted with this feature as I am, and good luck with getting your script exemplary.  I know from experience that you will be getting expert help on this forum.

_aleph_

Meds.  They're not just for breakfast anymore. :'(

Link to comment
Share on other sites

I ended up just using extended sleep delays to get around the issue. None of the loops I was trying worked unfortunately. Still haven't figured out why sometimes autoit 'detaches'  or references the previous iteration of the html from the webpage in IE11. Some scripts I've written have no such issue, and others I have to constantly reattach to get the updated page data after any change events...

Thank you guys for your input.

Edited by AJB
Link to comment
Share on other sites

I ended up just using extended sleep delays to get around the issue. None of the loops I was trying worked unfortunately. Still haven't figured out why sometimes autoit 'detaches'  or references the previous iteration of the html from the webpage in IE11. Some scripts I've written have no such issue, and others I have to constantly reattach to get the updated page data after any change events...

Thank you guys for your input.

did you try:
If StringInStr($body, "Page Loading") > 0 Then ;
The return value for
StringInStr is numeric not Boolean.
If the value of zero is returned that is likely treated as False.

 

 

 

Edited by philkryder
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...