Jump to content
AJB

While Loop confusion

Recommended Posts

AJB

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.

Share this post


Link to post
Share on other sites
mLipok
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:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for 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 API *

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 *

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 * 

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) * 

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 *

"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: 2018-03-17

Share this post


Link to post
Share on other sites
AJB

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.

Share this post


Link to post
Share on other sites
mikell

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

Share this post


Link to post
Share on other sites
AJB

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. 

Share this post


Link to post
Share on other sites
kaisies

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.

Share this post


Link to post
Share on other sites
mikell

Could you post the code which is before the While loop ?

Share this post


Link to post
Share on other sites
AJB
#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.

Share this post


Link to post
Share on other sites
aleph01

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. :'(

Share this post


Link to post
Share on other sites
AJB

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

Share this post


Link to post
Share on other sites
philkryder

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

Share this post


Link to post
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

  • Similar Content

    • FMS
      By FMS
      Hello,
      I try to get all the text from a news site around a subject.
      The first run I get all the text inside a attribute in an array.
      When i try to go back and reload another page it chrashes and think it because "$oIE.GoBack"
      I couldn't find anything in the help/forum around this subject.
      Do I need to reload the $oIE or something afther an X.GoBack?
      The error i got is :
      if $oTag2.GetAttribute("class") == "NewsDetail" Then if $oTag2^ ERROR I'm not shure why I got this error, maybe someone could explain?
      Also I'm open for some pointers in this test script because I'm pretty new in working whit the IE.UDF
      Maybe there is an simpler way to get the same results?

      test script:
      #include <IE.au3> #include <MsgBoxConstants.au3> #include <Array.au3> HotKeySet("{ESC}", "Terminate") Global $oIE = _IECreate("https://www.iex.nl/Zoeken/Nieuws.aspx?q=air%20france") ;get first subject Global $oLink1 = _IEGetObjById($oIE, "ctl00_ctl00_Content_LeftContent_NewsSearch_repNews_ctl00_linkNews") Sleep(500) _IEAction($oLink1, "click") Sleep(500) Global $oTags = _IETagNameGetCollection($oIE, "div") Global $aResults[1] For $oTag In $oTags if $oTag.GetAttribute("class") == "NewsDetail" Then _ArrayAdd($aResults, $oTag.innerTEXT) EndIf Next $aResults[0] = UBound($aResults) - 1 _ArrayDisplay($aResults, "Episodelist") ConsoleWrite($aResults[1] & @CRLF) $oIE.GoBack ;get second subject Global $oLink2 = _IEGetObjById($oIE, "ctl00_ctl00_Content_LeftContent_NewsSearch_repNews_ctl01_linkNews") Sleep(500) _IEAction($oLink2, "click") Sleep(500) Local $oTags2 = _IETagNameGetCollection($oIE, "div") Local $aResults2[1] For $oTag2 In $oTags2 if $oTag2.GetAttribute("class") == "NewsDetail" Then _ArrayAdd($aResults2, $oTag2.innerTEXT) EndIf Next $aResults2[0] = UBound($aResults2) - 1 ConsoleWrite($aResults2[1] & @CRLF) Func Terminate() _IEQuit($oIE) Exit EndFunc ;==>Terminate  
    • Aleksandar
      By Aleksandar
      So can anyone help me ? I need to restart program when condition is not met ...

    • SkysLastChance
      By SkysLastChance
      I am having a hard time understanding why this is not working. I was hoping some one could help explain it to me. 
      $tags = $oIE.document.GetElementsByTagName("input") For $tag in $tags $class_value = $tag.GetAttribute("class") If string($class_value) = "fTs-p3298-l0 wplEditControl" Then $target = $tag ExitLoop EndIF Next MsgBox(0,"",$target) If $target = "fTs-p3298-l0 wplEditControl" THEN MsgBox(0,"","itworked") I have tried 
       MsgBox(0,"",$target.Attribute)  MsgBox(0,"",$target.Value)  MsgBox(0,"",$target.InnerText) I would expect to see this in the msgbox
      fTs-p3298-l0 wplEditControl  
    • SkysLastChance
      By SkysLastChance
      I am trying to grab the id "in2xk_26" however it the characters before the underscore always change. (in the name too)
      Is there a way I can find a id or name by the last 3 charcters?
      Using something like "stringright?"
      So I would want to search for just "_26" in this case.
      This is assuming that there are no other _26
       

      #include <Excel.au3> #include <IE.au3> #include <GUIConstantsEx.au3> Global $iMousespeed = 25,$target = "",$TagName = "",$Value = "",$Atrribute = "" $oIE = _IEAttach("MEDITECH") $TagName = "input" $Value = "in2xk_26" $Attribute = "id" $tags = $oIE.document.GetElementsByTagName($TagName) ;TagName ------ MAKE SURE TO NAME THESE For $tag in $tags $class_value = $tag.GetAttribute($Attribute) ;Attribute ------ MAKE SURE TO NAME THESE If string($class_value) = $Value Then ;Value ------ MAKE SURE TO NAME THESE $target = $tag $iScreenX = _IEPropertyGet($target, "screenx") $iScreenY = _IEPropertyGet($target, "screeny") $iWidth = _IEPropertyGet($target, "width") $iHeight = _IEPropertyGet($target, "height") $oMouseCords = MouseMove($iScreenX + $iWidth / 2, $iScreenY + $iHeight / 2, $iMousespeed) MouseClick($MOUSE_CLICK_LEFT) ExitLoop EndIf Next  
       
    • SkysLastChance
      By SkysLastChance
      I was wondering how I read data inside of a iframe. I would like to be able to click something inside a iframe. However, I can't even find the tag. 
      The id and name change all the time so I can't use those. 
      The code highlighted in blue is what I am trying to click. (second picture)
      Here is what I have tried.
      $target = "" $tags = $oIE.document.GetElementsByTagName("div") For $tag in $tags $class_value = $tag.GetAttribute("class") If string($class_value) = "s_92 altstyle s_93 s_94" Then $target = $tag ConsoleWrite("Tag Found " & $target.outerText&@CRLF) ExitLoop EndIf Next  

       
       

×