2016-05-12 11 views
1

私はAJAXとjqueryでWebを扱おうとしています。このように、成功事例のなしで、私は特定のセクションに達するまでスクロールダウンしたいので、私は待つとECとのいくつかのアプローチをした:WebDriverWaitとexpected_conditionsを使ったwhileステートメントの使用

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に対処する方法がするまで何かをするために、ありますいくつかの要素が表示され、クリック可能ですか?

EDIT:

私はJavaScriptを使用して、いくつかの汚い手口をしましたが、間違いなく私の目標に到達するためのニシキヘビの方法ではありません。

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

関連する問題