简体   繁体   中英

Using while statement with WebDriverWait and expected_conditions

I'm trying to deal with a web with AJAX and jquery. I want to scroll down until reach certain section, so I did some approaches with wait and EC, without sucess, like this:

 scroll_bottom = """$('html, body').animate({scrollTop:$(document).height()},'fast');"""
 from selenium.webdriver.common.by import By
 # from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.support import expected_conditions as EC
 # wait = WebDriverWait(driver,10)
 while EC.element_to_be_clickable((By.ID,"STOP_HERE")):
     driver.execute_script(scroll_bottom)

Is there any way to deal with wait and EC, in order to do something until some element is visible and/or clickable?

EDIT:

I did some dirty tricks with javascript, but definitely is not the pythonic way to reach my goal.

def scroll_b():
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    driver.execute_script(load_jquery)
    wait = WebDriverWait(driver,10)
    js = """return document.getElementById("STOP_HERE")"""
    selector = driver.execute_script(js)
    while not  selector :
        driver.execute_script(scroll_bottom)
        time.sleep(1)
        selector = driver.execute_script(js)
    print("END OF SCROLL")

Thats not how the built in Expected Conditions are intended to work. Generally speaking, once you activate them, they block until whatever condition returns True.

I think what you want is a custom expected condition. This is untested:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

scroll_bottom = """$('html, body').animate({scrollTop:$(document).height()},'fast');"""

def scroll_wait(driver):
    # See if your element is present
    # Use the plural 'elements' to prevent throwing an exception
    # if the element is not yet present
    elem = driver.find_elements_by_id("STOP_HERE")

    # Now use a conditional to control the Wait
    if elem and elem[0].is_enabled and elem[0].is_displayed:
        # Returning True (or something that is truthy, like a non-empty list)
        # will cause the selenium Wait to exit
        return elem[0]
    else:
        # Scroll down more
        driver.execute_script(scroll_bottom)

        # Returning False will cause the Wait to wait and then retry
        return False

# Now use your custom expected condition with a Wait
TIMEOUT = 30  # 30 second timeout
WebDriverWait(driver, TIMEOUT, poll_frequency=0.25).until(scroll_wait)

What's nice about this approach is that it will throw an exception after 30 seconds (or whatever you set TIMEOUT to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM