2016-10-07 118 views
1

我颳了一個動態頁面,要求用戶多次單擊「加載更多結果」按鈕才能獲取所有數據。有更好的方法來處理顯示時點擊元素的任務嗎?Python selenium點擊元素,同時顯示

def clickon(xpath): 
    try: 
     element = driver.find_element_by_xpath(xpath) 
    except: 
     print "RETRYING CLICKON() for %s" % (xpath) 
     time.sleep(1) 
     clickon(xpath) 
    else: 
     element.click() 
     time.sleep(3) 

def click_element_while_displayed(xpath): 
    element = driver.find_element_by_xpath(xpath) 
    try: 
     while element.is_displayed(): 
      clickon(xpath) 
    except: 
     pass 

回答

3

我懷疑你是問這個問題,因爲目前的解決方案很慢。這主要是因爲你有這些硬編碼的延遲等待比他們通常應該更多的延遲。爲了解決這個問題,我會開始使用Explicit Waits - 初始化一個無限循環,並打破它一旦停止硒等按鈕可以點擊:

from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.common.exceptions import TimeoutException 

wait = WebDriverWait(driver, 10) 

while True: 
    try: 
     element = wait.until(EC.element_to_be_clickable((By.XPATH, xpath))) 
     element.click() 
    except TimeoutException: 
     break # cannot click the button anymore 

    # TODO: wait for the results of the click action 

現在最後TODO部分也很重要 - 在這裏,我建議你等待對於一個特定的條件,可能表明點擊導致頁面上的東西 - 例如,更多的結果加載。例如,您可以使用類似於this one的自定義預期條件。