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

    • nassausky
      By nassausky
      Hi all,
       
      Anyone have any idea how to close all open tabs except a specific one I manually open.  Assuming I don't know what is open in all the tabs except just the one I want to keep open.
       
      I didn't want to use sendkeys and I was trying to use the following code to list the title (or url) of the 3 open tabs and  after I got that part working I would just close the other 2. This sample only displays the title of the first open tab
      #include <IE.au3> Const $ie_new_in_tab = 0x0800 $oIE = _IECreate("https://www.autoitscript.com") __IENavigate($oIE, "https://www.autoitscript.com/forum/", 1, $ie_new_in_tab) ;(obj,url,wait,param) __IENavigate($oIE, "https://www.google.com/", 1, $ie_new_in_tab) ;(obj,url,wait,param) Local $aIE[1] $aIE[0] = 0 Local $i = 1, $oIE While 1     $oIE = _IEAttach("", "instance", $i)     If @error = $_IEStatus_NoMatch Then ExitLoop     ConsoleWrite(_IEPropertyGet($oIE, "title") & @CRLF)     ReDim $aIE[$i + 1]     $aIE[$i] = $oIE ;each item holds object     $aIE[0] = $i ;first item holds count     $i += 1 WEnd MsgBox($MB_SYSTEMMODAL, "Browsers Found", "Number of browser instances in the array: " & $aIE[0]) ; This doesn't return the list of tabs in the console just the first tab  
      Thanks for any and all help
    • toto22
      By toto22
      I'm trying to click on Java Dropbox using IE. However, I'm running into problems. There is a Dropbox "Please Select" with two options "Buy" and "Sell".
      I'm able to click on a drop box (please see code below) but i'm unable to select "Buy" or "Sell"".
      Local $sMyString = "Please Select" ;############ ENTER ############# Local $oLinks = _IELinkGetCollection($oIE) For $oLink In $oLinks Local $sLinkText = _IEPropertyGet($oLink, "innerText") If StringInStr($sLinkText, $sMyString) Then _IEAction($oLink, "click") ExitLoop EndIf Next  
      Please help
       
         
    • Gowrisankar
      By Gowrisankar
      Hello everyone,
      I'm working on a task where, a PDF file is opened (in IE browser) when I click a link in a website.
      I have to read the first page of the PDF to find particular strings. Can you please share some ideas?
    • Seminko
      By Seminko
      Hey,
      i would like to set a value into an INPUT field.
      Checked the _IEFormElementSetValue function but that does require _IEFormGetObjByName and this is where the problem comes in. The input field I want to write to is not a part of a form tag. It is part of a table.
      <input type="text" class="w2" id="nabidka_vozidel_formular_tach_od" name="nabidka_vozidel_formular_tach_od" onchange="GLOBAL.pocetInzerceNZ(&quot;nabidka_vozidel_formular&quot;,&quot;tach_od&quot;,&quot;&quot;);" autocomplete="off"> I tried this but that didn't work:
      $oDownloadSamples = _IEGetObjById($oIE, "nabidka_vozidel_formular_tach_od") _IEFormElementSetValue($oDownloadSamples, "123") If you want to try the site I'm working with is https://www.tipcars.cz/. There is a menu on the top left hand side and if you click the "vyhledat" button the input fields will show up.
      Thanks
    • Seminko
      By Seminko
      I am now able to populate the dropdown menus at https://www.tipcars.com/.
      The dropdowns are dynamic and do not have a Text value, only ids.
      Is there a way to get all the available options from a dropdown?
      $url = "https://www.tipcars.com/" $oIE = _IECreate($url) _IELoadWait($oIE) $oDownloadSamples = _IEGetObjById($oIE, "homepage_vyhl_frm_vozidlo") _IEFormElementOptionSelect($oDownloadSamples, "C") Above code, populates ID 'C' into the 'druh' dropdown, which results in selecting 'užitkové'. 
      Is there a way so I can grab all of the options from the dropdown menu? I could easily grab all the IDs but I am afraid they will change in the future so I would much rather match the text titles and assign the option IDs grabbed from site.
      This is what the options are according to Chrome:
      <select class="w1"id="homepage_vyhl_frm_vozidlo"name="homepage_vyhl_frm_vozidlo"onchange="try{NABIDKA_VOZIDEL_FORMULAR.naplnSelectZnacka('homepage_vyhl_frm');GLOBAL.pocetInzerceHZ('homepage_vyhl_frm','vozidlo');}catch(ex){odeslatJsChybu('formHOMEPAGE onChange 1: ' + ex.message, 'formHomePage onChange 1', -1);}"> <option value="A" style="color: black;">osobní a terénní (56 334)</option> <option value="C" style="color: black;">užitkové (4 333)</option> <option value="D" style="color: black;">nákladní (3 742)</option> <option value="E" style="color: black;">autobusy (56)</option> <option value="F" style="color: black;">obytné (373)</option> <option value="G" style="color: black;">přívěsy (1 179)</option> <option value="J" style="color: black;">motorky (780)</option> <option value="S" style="color: black;">pracovní stroje (605)</option> <option value="L" style="color: black;">ostatní (235)</option></select> Also, this cannot be grabbed by _INetGetSource.
      Thanks