Appium 【已解决】元素不能定位的时候 直接退出报错,is_display() 这样的函数怎么使用?

敌方解说员 · 2014年11月18日 · 最后由 唐僧之妈 回复于 2014年11月18日 · 1714 次阅读

def test_findkeyboard(self):
    el = self.driver.find_element_by_class_name('UIAKeyboard')
    print(el.is_displayed())

执行以上 test 的时候直接报错
An element could not be located on the page using the given search parameters.

求助下 is_display() 这样的函数应该怎么使用

/usr/bin/python "/Applications/PyCharm CE.app/helpers/pycharm/utrunner.py" /Users/Alfred/sample-code-master/sample-code/examples/python/sapi_login_test.py::SapiHomePageTests::test_findkeyboard true
Testing started at 下午5:57 ...

Error
Traceback (most recent call last):
  File "/Users/Alfred/sample-code-master/sample-code/examples/python/sapi_login_test.py", line 44, in test_findkeyboard
    el = self.driver.find_element_by_class_name('UIAKeyboard')
  File "/Library/Python/2.7/site-packages/selenium-2.41.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 343, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
  File "/Library/Python/2.7/site-packages/selenium-2.41.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 655, in find_element
    {'using': by, 'value': value})['value']
  File "/Library/Python/2.7/site-packages/selenium-2.41.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 166, in execute
    self.error_handler.check_response(response)
  File "build/bdist.macosx-10.9-intel/egg/appium/webdriver/errorhandler.py", line 29, in check_response
    raise wde
NoSuchElementException: Message: u'An element could not be located on the page using the given search parameters.' 
共收到 6 条回复 时间 点赞

第一个问题:没有找到元素而导致脚本退出,可以使用 Try Catch 来捕获异常,从而可以继续下面的测试
第二个问题: is_displayed() 应该就是这样使用的,可以判断元素对用户是否可见,但是根据你的报错信息,这个元素未找见并导致脚本执行失败,所以 el.is_displayed() 自然是不会执行

#1 楼 @xiaomayi0323 多谢回答啊,我看 appium 官方 给出的 case 里面 也没有使用 try catch 的结构啊 ,为啥他的那个能过,这个是有特别的配置么

try catch 只是为了捕获异常 至于为啥能过,楼上已经解释很清楚了

#3 楼 @kasi 那在键盘展示之前 必然要先 使用 find 来定位,再判断 is_display() 啊

能否求一个 判断键盘是否展示的 代码段?

#1 楼 @xiaomayi0323 应该是我问题没有描述清楚 , 其实我是想问 如果类似 keyboard 这样的东西,本身在页面上不存在,在后来被动态的添加, 在没有被添加的时候 去执行 find 肯定会报错,我要怎么判断他是不是已经被添加了呢

#5 楼 @wozaihouma
简单的处理方式就是等,比如:

for i in range(3):
    try:
        self.driver.find_element_by_class_name('UIAKeyboard')
    except NoSuchElementException:
        #等待三秒后再Find一次
        time.sleep(3)
    else:
        #如果Keyboard出现,则处理与Keyboard相关的逻辑,如点击操作,并跳出循环
        self.driver.find_element_by_class_name('UIAKeyboard').click()
        break
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册