2017-04-12 117 views
-2

我想驗證一行是否顯示。我使用python和Selenium。這裏是我到目前爲止已經試過Python IF語句無法識別其他:

try: 
     row = self.driver.find_element_by_xpath(<row6>).is_displayed() 
     if row is False: 
      print("button is not displayed. Test is passed") 
     else: 
      do stuff 
    except: 
     NoSuchElementException 

我努力實現以下目標: 頁#1只顯示一個按鈕,如果頁#2已經排< 6.

我仍然有邏輯寫條件 - >如果行是假的:。但是,如果它是錯誤的,它應該至少打印字符串。

此刻,else:在我的代碼中不起作用。沒有顯示錯誤,但嘗試:退出NoSuchElementException。

更新:我也嘗試了下面的代碼,我驗證按鈕是否顯示在頁面#1上,轉到頁面#2並驗證row6是否存在。如果顯示按鈕,這將起作用。如果沒有顯示按鈕,它拋出一個錯誤:NoSuchElementException異常:消息:找不到元素:

try: 
     button = self.driver.find_element_by_xpath(PATH) 
     if button.is_displayed(): 
      do stuff 
      row = self.driver.find_element_by_xpath(<row6>) 
      if row.is_displayed(): 
       do stuff 
      else: 
       do stuff 
    except: 
     button = self.driver.find_element_by_xpath("PATH").is_displayed() 
     if button is False: 
      print("button is hidden. Test is passed") 

上我怎樣才能使這項工作任何建議?

+4

你期望有什麼東西可以循環嗎? '如果'不啓動循環。 – Matthias

+0

是的。所以如果row爲False: - >按鈕不顯示,如果row爲True,則顯示按鈕。無論哪種方式,測試都是有效的。 – Bubbles

+1

我很困惑你的問題和你正在努力完成的工作 – heinst

回答

0

也許沒有隱藏row6被發現並引發異常。

你的except語法是錯誤的:它會捕獲所有異常,然後對NoSuchElementException對象不做任何處理。

您是不是要找:

except NoSuchElementException: 
    #do something when no row6 found 
+0

感謝您的語法修正。但是,如果您檢入我的代碼,變量'''保存在'try'語句中。如果它不存在並添加在'except:'下,selenium顯示3個不同的錯誤1)InvalidSelectorException:2)InvalidSelectorError:3)SyntaxError:該表達式不是合法表達式。不幸的是,這並沒有解決我的問題。 – Bubbles

0

我不知道硒,但它聽起來像是這裏可能有多個異常,並非所有相同類型的,而不是在那裏你可以期望他們發生。例如,當row.is_displayed()的計算結果爲True時,一切正常,但會拋出異常 - 這表明row可能是None或其他意外結果。我粗略地看了一眼docs,但我看不到馬上。

反正 - 調試這個問題,嘗試把你的代碼的不同部分到try-except塊:

try: 
    button = self.driver.find_element_by_xpath(PATH) 
    if button.is_displayed(): 
     do stuff 
     try: 
      row = self.driver.find_element_by_xpath(<row6>) 
     except: # <-- Better if you test against a specific Exception! 
      print(" something is wrong with row! ") 
     try: 
      if row.is_displayed(): 
       do stuff 
      else: 
       do stuff 
     except: # <-- Better if you test against a specific Exception! 
      print(" something is wrong with using row!") 
except: # <-- Better if you test against a specific Exception! 
    button = self.driver.find_element_by_xpath("PATH").is_displayed() 
    if button is False: 
     print("button is hidden. Test is passed") 

此外,儘量把代碼的最小量每try-except裏面,讓你知道在哪裏的例外是來自(哪裏。

+0

感謝您的回覆。我在線研究這個問題的解決方案。這似乎是驗證Selenium中元素「不可見」的一個常見問題。 – Bubbles