解決利用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
..[略]..
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 發生..')
留言
張貼留言