2016-05-12 106 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