2016-05-12 33 views
1

我试图处理与AJAX和jQuery的网站。我要向下滚动,直到达到一定的部分,所以我也有等待和欧盟的一些方法,没有sucess,像这样:使用while语句与WebDriverWait和expected_conditions

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) 

有什么办法对付等待和EC,为了做一些事情,直到某些元素是可见的和/或可点击的?

编辑:

我做了一些肮脏的把戏与JavaScript,但绝对不是我达到目标的Python的方式。

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") 

回答

1

这并不是说建立在预期条件的内容是如何工作的。一般来说,一旦你激活它们,它们就会阻塞,直到任何条件返回True。

我想你想要的是一种自定义的预期条件。这是未经测试:

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) 

什么是对这种做法不错的是,它会在30秒后抛出异常(或者你设置的超时)。

+0

这是一个聪明的解决方案,比我的方式更好。可惜的是webdriver是多么的可惜,以及它如何缺乏一种对语句友好的功能,以及“只是期望一种条件”。 谢谢! – peluzza