4

In my test, I need to wait for text until it will be loaded.

I have a list of countries and cities. After I choice country I must wait until cities will be loaded. How I can wait without time.sleep()?

time.sleep(2)

select_country = Select(self.browser.css("#country_id"))
select_country.select_by_visible_text("Russia")

time.sleep(2)

select_city = Select(self.browser.css("#city_id"))
select_city.select_by_visible_text("Moscow") 
1
  • Can you add the HTML source?
    – FDM
    Jul 30, 2017 at 8:49

2 Answers 2

7

You can use Explicit Wait:
An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code.

OPTION-1:

driver.implicitly_wait(10) # seconds
select_country = Select(self.browser.css("#country_id"))
select_country.select_by_visible_text("Russia")

city = driver.find_element_by_css_selector("#city_id")

wait = WebDriverWait(driver, 10)
city_dropDown = wait.until(expected_conditions.visibility_of_element_located(city))
select_city = Select(city_dropDown)
select_city.select_by_visible_text("Moscow") 

OPTION-2:

from selenium.webdriver.support import expected_conditions as EC

select_country = Select(self.browser.css("#country_id"))
select_country.select_by_visible_text("Russia")

wait = WebDriverWait(driver, 10)
element=wait.until(EC.element_to_be_selected(driver.find_element_by_css_selector("#city_id")))
select_city = Select(element)
select_city.select_by_visible_text("Moscow") 

OPTION-3:

select_country = Select(self.browser.css("#country_id"))
select_country.select_by_visible_text("Russia")

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "city"))
//---------use other element locators too like xpath/css_selector/css_name
    )
finally:
    select_city = Select(element)
    select_city.select_by_visible_text("Moscow") 

OPTION-4:

You can also try with Implicit Waits:

An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available.

driver.implicitly_wait(10) # seconds
select_country = Select(self.browser.css("#country_id"))
select_country.select_by_visible_text("Russia")
driver.implicitly_wait(10) # seconds
select_city = Select(self.browser.css("#city_id"))
select_city.select_by_visible_text("Moscow")    
1
  • 1
    Good one....! I'm also searching for the same issue & Now fixed with the above code. Thanks, @Bharat.
    – Sophia
    Aug 1, 2017 at 10:01
1

You can use the waits that Selenium provides you in order to wait for countries to load. You can either use implicit wait or explicit wait (recommended).

Please read the Selenium documentation for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.