Home > Back-end >  Python Selenium - Wait until Element is loaded
Python Selenium - Wait until Element is loaded

Time:01-03

I often have the problem with Selenium that the script crashes because I want to access an element that is not loaded yet.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method": "xpath", "selector":"//*[@id="ipv4_info"]/span[3]"}

Currently I do it that way, that I put a time.sleep(30) before such places, but sometimes it takes longer or shorter until the element loads.

Is there any way to wait until the element is loaded and as soon as it is loaded immediately continue with the rest of the code?

CodePudding user response:

To locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following Locator Strategies:

  • XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id="ipv4_info"]/span[3]")))
    
  • CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ipv4_info span:nth-child(3)")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • Related