Search code examples
pythonpython-2.7seleniumchrome-web-driver

run a while loop untill a css selector is present on web page


I need to run this loop until ".loadMore" css selector is present on webpage:

while ec.presence_of_element_located('.loadMore'):
        element_number = 25 * i
        wait = WebDriverWait(driver, time1);
        sub_button = (by, hook + str(element_number))
        wait.until(ec.presence_of_element_located(sub_button))
        driver.find_element_by_css_selector(button).click()
        time.sleep(5)  # Makes the page wait for the element to change
        i += 1

Solution

  • Write your def to check for element presence

    from selenium.common.exceptions import NoSuchElementException        
    def check_element_presence(selector):
        try:
            webdriver.find_element_by_css_selector(selector)
        except NoSuchElementException:
            return False
        return True
    

    Now run it like

    while check_element_presence('.loadmore'):
       ...
       ...
       ...