2016-02-11 56 views
1

我正在學習用於某些QA自動化任務的python和selenium。我正在研究框架的導航部分,而且我有一個非常不一致的測試。無需更改測試或站點,它有時會通過,有時會失敗。它看起來沒有執行Hover動作,然後在找不到子菜單鏈接時拋出異常。使用Python進行易碎測試

轉到功能:

def goto(driver, section, subsection): 
     if subsection != "None": 
      hover_over = driver.find_element_by_link_text(section) 
      hover = selenium.webdriver.ActionChains(driver).move_to_element(hover_over) 
      hover.perform() 
      driver.find_element_by_link_text(subsection).click() 
     else: 
      driver.find_element_by_link_text(section).click() 

基本上部變量是需要被懸停打開子菜單的第一菜單項。子部分變量是要被點擊的子菜單鏈接的文本。

我能想到的唯一原因就是它太脆弱了,站點響應時間太差,但是Selenium沒有等到先前的操作完成後再繼續下一個操作?

回答

1

是的,這聽起來像是一個時間問題。

讓我們更可靠通過添加explicit wait點擊子菜單前:

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

def goto(driver, section, subsection): 
    if subsection != "None": 
     hover_over = driver.find_element_by_link_text(section) 
     hover = selenium.webdriver.ActionChains(driver).move_to_element(hover_over) 
     hover.perform() 

     # IMPROVEMENT HERE 
     WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, subsection))).click() 
    else: 
     driver.find_element_by_link_text(section).click() 
+0

太感謝你了,剛跑五次沒有失敗! –