2017-04-12 92 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