AJB

While Loop confusion

12 posts in this topic

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



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 - BETA * 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 * Best coding practices * 

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: 2017-06-04

Share this post


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

Share this post


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

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites

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

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

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

#12 ·  Posted (edited)

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

    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening everyone
      Before all, I want to say that I'm doing this script to see how _IE* functions work, and see if my studs can hack a quiz I'm working on.
      I want to clarify that I'm not automating any game, bypassing any CAPTCHAs, or anything that could damage anyone.
      I was trying to autofill a form, based on which question is displayed.
      The question is always stored in here:
      <header> <h1><span class="questionid">1. </span>Here goes the question</h1> </header> And answers are stored in here:
      <ul class="answers"> <li><label><span><input id="answer_0" name="answer[]" type="radio" value="0">Answer 1</span></label></li> <li><label><span><input id="answer_1" name="answer[]" type="radio" value="1">Answer 2</span></label></li> <li><label><span><input id="answer_2" name="answer[]" type="radio" value="2">Anwser 3</span></label></li> <li><label><span><input id="answer_3" name="answer[]" type="radio" value="3">Answer 4</span></label></li> </ul></fieldset></form></div> And, there are 15 questions like this.
      How can automatically fill my form?
      Thanks in advance
      Francesco
    • Omnitica
      By Omnitica
      Hello!
      I'm new to the forums! Couldn't find any threads covering this issue. Sorry if I'm wrong.

      I'm having problems changing the text/value of a input box. The particular box doesn't have a name or id, just: class="jq_hotkeys_enabled form-control".
      This class appears multiple times throughout the source, so I don't think It's right to reference that object. 
      See image 1.
      However, I've managed to find a object with the name "ctl00$content$ctrl$ucServiceTime$rpServicetimes$ctl00$edtHiddenResourceHelper" which contains the value of the input box, and the id for the person in the dropdown/combobox left of it. (with "dummy-1" selected).
      See image 2.
      As you can see the value is 3982,4545     ( name , time )
      But when I try to change the value of it by doing:
      #include <IE.au3> Local $oIE = _IEAttach(WinGetHandle("[CLASS:IEFrame]"),"embedded") Local $oForm = _IEFormGetObjByName($oIE, "aspnetForm") Local $oInput = _IEFormElementGetObjByName($oForm, "ctl00$content$ctrl$ucServiceTime$rpServicetimes$ctl00$edtHiddenResourceHelper") _IEFormElementSetValue($oInput, "3982,1337") The box doesn't get its new value. I  can see in the source that it's changed though.
      See image 3.
       
      However, if I do: 
      #include <IE.au3> Local $oIE = _IEAttach(WinGetHandle("[CLASS:IEFrame]"),"embedded") Local $oForm = _IEFormGetObjByName($oIE, "aspnetForm") Local $oInput = _IEFormElementGetObjByName($oForm, "ctl00$content$ctrl$ucServiceTime$rpServicetimes$ctl00$edtHiddenResourceHelper") _IEFormElementSetValue($oInput, "3982,1337") $oIE.document.parentwindow.execScript("theForm.submit()") ; But it needs to reload the page The box gets its new value after the page reloads by the theForm.submit() function. 
      This is a bit unfortunate as I want the changes to happen instantly like when I type in the box with the keyboard... or select in the combobox.
      Maybe someone knows how I can do this? Looking forward to an answer! 
      Thanks in advance.
       
      Note: Unfortunately I can't provide with the real URL as it is constricted to employees in the company I work for, but let me know If I should provide anything else.
       



    • Eli_jahbot
      By Eli_jahbot
      my esteemed autoits,
      i need your help once again. The bold and italics below are what i will be referring to. I need a message box to exit the script if Cancel is pressed and to continue the script if OK is pressed. I have tried multiple ways to do this to no avail. Can someone please breakdown how i go about this via Message box, and or Input box as I'm sure they will follow the same logic. I appreciate your time and assistance.
       
      Example:
      global $url, $username, $password, $sspassword
      $url = "https://securegateway.fairview.org"
      $username = "XXX"
      $password = "YYY"
      $sspassword = "ZZZ"
      #include <Constants.au3>
      #include <msgboxconstants.au3>
      ShellExecute ($url)
      WinWaitActive("window")
      send($username)
      send("{tab}")
      send($password)
      send("{enter}")
      msgbox($mb_okcancel, "Wait for the page to load then select OK to continue script", "Wait for the page to load then select OK to continue script")
      if($idok)
      send("+{tab 8}")
      send("{enter}")
      if ($idcancel) then Exit
      EndIf
    • ur
      By ur
      For the below form, I am able to automate using below code for textboxes.

      #include <IE.au3> Local $oIE = _IEAttach("http://localhost:18170/MartAdmin/", "url") _IELoadWait($oIE) $Search = _IEGetObjById($oIE,"x-auto-16-input") _IEPropertySet($Search, 'innerText','Uday KIran') $Search = _IEGetObjById($oIE,"x-auto-18-input") _IEPropertySet($Search, 'innerText','Uday KIran') But for the Login button, there is no id or name.
      The html code when I click on Inspect element in browser, shown below.
      <button tabindex="0" class="x-btn-text" style="width: 64px; position: relative;" type="button">Log In</button> Please let me know how to click this.?
       
    • jonson1986
      By jonson1986
      Hey,
      I'm trying to select language from drop-down menu on a webpage by _IEGetObjById but it's  not working, It mean autoit open the page but unable to select my desired value not even by matching text or by value, I'm looking for kind help...I've pastes my Autoit codes below along with source codes(using ie) of the webpage ;
      #include <IE.au3> $site = "http://example.com/upload" $oIE = _IECreate($site) $oDownloadSamples = _IEGetObjById($oIE, "language") $oDownloadSamplesSelect = _IETagNameGetCollection($oDownloadSamples, "select", "language") $oDownloadSamplesSelect.focus _IEFormElementOptionSelect($oDownloadSamplesSelect, "French", 1, "byText") Sleep (1000) _IEFormElementOptionSelect($oDownloadSamplesSelect, "2", 1, "byValue") HTML Codes using IE:
      <html> <head> <div class="form-row"> <div class="col-7"> <label>Language</label> <select name="language" class="select" id="language"> <option value="1">English</option> <option value="2">French</option> <option value="3">German</option> <option value="4">Italian</option> <option value="5">Japanese</option> <option value="6">Spanish</option> <option value="7">Russian</option> <option value="8">Hindi</option> <option value="9">Arabic</option> <option value="10">Chinese</option> <option value="11">Dutch</option> <option value="12">Finnish</option> <option value="13">Korean</option> <option value="14">Norwegian</option> <option value="15">Portuguese</option> <option value="16">Romanian</option> <option value="17">Serbian</option> <option value="18">Croatian</option> <option value="20">Polish</option> <option value="21">Afar</option> <option value="22">Abkhazian</option> <option value="23">Afrikaans</option> <option value="24">Amharic</option> <option value="25">Assamese</option> <option value="26">Aymara</option> <option value="27">Azerbaijani</option> <option value="28">Bashkir</option> <option value="29">Belarusian</option> <option value="30">Bulgarian</option> <option value="31">Bihari</option> <option value="32">Bislama</option> <option value="33">Bengali/Bangla</option> <option value="34">Tibetan</option> <option value="35">Breton</option> <option value="36">Catalan</option> <option value="37">Corsican</option> <option value="38">Czech</option> <option value="39">Welsh</option> <option value="40">Danish</option> <option value="41">Bhutani</option> <option value="42">Greek</option> <option value="43">Esperanto</option> <option value="44">Estonian</option> <option value="45">Basque</option> <option value="46">Persian</option> <option value="47">Fiji</option> <option value="48">Faeroese</option> <option value="49">Frisian</option> <option value="50">Irish</option> <option value="51">Scots/Gaelic</option> <option value="52">Galician</option> <option value="53">Guarani</option> <option value="54">Gujarati</option> <option value="55">Hausa</option> <option value="56">Hungarian</option> <option value="57">Armenian</option> <option value="58">Interlingua</option> <option value="59">Interlingue</option> <option value="60">Inupiak</option> <option value="61">Indonesian</option> <option value="62">Icelandic</option> <option value="63">Hebrew</option> <option value="64">Yiddish</option> <option value="65">Javanese</option> <option value="66">Georgian</option> <option value="67">Kazakh</option> <option value="68">Greenlandic</option> <option value="69">Cambodian</option> <option value="70">Kannada</option> <option value="71">Kashmiri</option> <option value="72">Kurdish</option> <option value="73">Kirghiz</option> <option value="74">Latin</option> <option value="75">Lingala</option> <option value="76">Laothian</option> <option value="77">Lithuanian</option> <option value="78">Latvian/Lettish</option> <option value="79">Malagasy</option> <option value="80">Maori</option> <option value="81">Macedonian</option> <option value="82">Malayalam</option> <option value="83">Mongolian</option> <option value="84">Moldavian</option> <option value="85">Marathi</option> <option value="86">Malay</option> <option value="87">Maltese</option> <option value="88">Burmese</option> <option value="89">Nauru</option> <option value="90">Nepali</option> <option value="91">Occitan</option> <option value="92">(Afan)/Oromoor/Oriya</option> <option value="93">Punjabi</option> <option value="94">Pashto/Pushto</option> <option value="95">Quechua</option> <option value="96">Rhaeto-Romance</option> <option value="97">Kirundi</option> <option value="98">Kinyarwanda</option> <option value="99">Sanskrit</option> <option value="100">Sindhi</option> <option value="101">Sangro</option> <option value="102">Serbo-Croatian</option> <option value="103">Singhalese</option> <option value="104">Slovak</option> <option value="105">Slovenian</option> <option value="106">Samoan</option> <option value="107">Shona</option> <option value="108">Somali</option> <option value="109">Albanian</option> <option value="110">Siswati</option> <option value="111">Sesotho</option> <option value="112">Sundanese</option> <option value="113">Swedish</option> <option value="114">Swahili</option> <option value="115">Tamil</option> <option value="116">Telugu</option> <option value="117">Tajik</option> <option value="118">Thai</option> <option value="119">Tigrinya</option> <option value="120">Turkmen</option> <option value="121">Tagalog</option> <option value="122">Setswana</option> <option value="123">Tonga</option> <option value="124">Turkish</option> <option value="125">Tsonga</option> <option value="126">Tatar</option> <option value="127">Twi</option> <option value="128">Ukrainian</option> <option value="129">Urdu</option> <option value="130">Uzbek</option> <option value="131">Vietnamese</option> <option value="132">Volapuk</option> <option value="133">Wolof</option> <option value="134">Xhosa</option> <option value="135">Yoruba</option> <option value="136">Zulu</option> <option value="19">Other</option> </select> </div> </main> </body> </html>