解決利用Selenium執行UnitTest:送出POST後 , getElement卻出現StaleElementReferenceException問題

原因:POST送出前後,會有時間差且兩張頁面是不同的,所以POST送出後沒有等待,

直接找Response結果,會出現StaleElementReferenceException例外。(跟你說找不到)

解法:在POST送出後,使用WebDriverWait等一下,直到你要找的Element出現。

註:呼~~花了好多時間找答案,還好有解決。

參考來源:https://selenium-python.readthedocs.io/waits.html

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
 
..[略]..

# User輸入待辦事項
    inputbox.send_keys('Buy dinner')

    # User Click Enter Button & Page will show "1:Buy dinner" , which is a to-do list item.
    inputbox.send_keys(Keys.ENTER)
    
    # 除錯方式,在執行時,使用time.sleep來暫停測試
    # import time
    # time.sleep(60)

    # table = self.browser.find_element_by_id('id_list_table') #selenium找不到 'id_list_table'
    table = None
    table = WebDriverWait(self.browser , 10).until(
      EC.presence_of_element_located((By.ID, "id_list_table"))
    )
    
    if table != None:
      rows = table.find_elements_by_tag_name('tr'#所有行(ROW)
      self.assertIn('1: Buy dinner',[row.text for row in rows])
    else:
      print('StaleElementReferenceException 發生..')

留言

這個網誌中的熱門文章

溪和食品有限公司 - 觀光工廠接待人員(薪約30K.免費供餐),今天投遞此份工作。

載入JavaScript code的最佳時機