1

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?

1 Answer 1

4

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
    
2
  • What does the 20 stand for? Commented Aug 9, 2023 at 16:17
  • 1
    @AbduladilSunnat the timeout in seconds Commented Nov 22, 2023 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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