0

While automation with Python Selenium, I came across a scenario where a textbox Total Amount gets populated based on some processing. The textbox takes some time to get populated. I use the below code to fetch the data, but the data I get is ""(empty value). If I use sleep I get the total amount correctly. Could someone let me know how to explicitly wait for the change of attribute value of the element.

driver.find_element_by_css_selector('input#TotalAmount').get_attribute("value")
JeffC
  • 22,180
  • 5
  • 32
  • 55
JCDani
  • 307
  • 7
  • 20
  • I have tried as mentioned in the link but still couldn't get it. Do we have any other approach? – JCDani May 25 '18 at 06:22

2 Answers2

0

I believe you're on the right track using time.sleep to wait for the value to be populated but I think you could improve it using a while True block to continue trying until a value is returned.

Consider the following:

from selenium.common.exceptions import WebDriverException
import time

MAX_TIME = 5  # This is the maximum time that the loop executes for
start_time = time.time()

while True:
    # Attempt to select the element from the browser
    val = driver.find_element_by_css_selector('input#TotalAmount').get_attribute("value")

    # If an empty string is not returned, break out
    if val != '':
        break

    # If the maximum execution time has been exceeded, raise a WebDriverException
    elif time.time() - start_time > MAX_TIME:
        raise WebDriverException

    # Otherwise sleep for 0.5s and retry
    else:
        time.sleep(0.5)

In this example, the while block will continue executing until a value other than '' is returned or if the execution time exceeds 5 seconds it raises a WebDriverException

ScottMcC
  • 4,094
  • 1
  • 27
  • 35
  • This is a very dangerous statement to use in my opinion. In case of a defect that causes the data not to be populated it would go into an endless loop. Secondly, in any automation usage of sleep is a bad practice, because if one guy do it, every member in the team will start doing it. Please help me with any selenium methods. – JCDani May 25 '18 at 06:22
  • It's not dangerous if the loop is managed correctly. For example, I've updated my answer with a loop termination once 5 seconds has passed, with the opportunity to raise an exception. Alternatively if you don't want to use a while True loop, put the timeout statement as a condition for your while loop. – ScottMcC May 25 '18 at 06:35
-1

I don't have specific details about what code to use, but it looks like the solution is to use a Selenium Wait to wait until the condition you're looking for.

Lucretiel
  • 3,145
  • 1
  • 24
  • 52