环境:
Mac:10.9.3
Xcode:5.1.1
iOS Simulator: 7.1
Appium:1.1.0
Appium-Python-Client: 0.6

最新的 Appium 中,在 sample-code/examples/python 目录下有一个 ios_simple.py 示例脚本,运行其中的

def test_scroll(self):
        els = self.driver.find_elements_by_class_name('UIAButton')
        els[5].click()

        sleep(1)
        el = self.driver.find_element_by_name('OK')
        el.click()

        sleep(1)
        el = self.driver.find_element_by_xpath('//UIAMapView[1]')

        location = el.location
        print location
        self.driver.swipe(startx=location['x'], starty=location['y'], endx=0.5, endy=location['y'], duration=0.8)

运行后,Python 会先报出 “IndexError: list index out of range”,这是数据越界,没有找到对应的元素,这个不是重点,修改为正确的下标后就可以了。

els = self.driver.find_elements_by_class_name('UIAButton')
        els[3].click()

另一个问题,这句

self.driver.swipe(startx=location['x'], starty=location['y'], endx=0.5, endy=location['y'], duration=0.8)

在 IDE 中会提示:Unexpected argument,查看源码后,发现需要修改为(看来 Appium 的开发者们太忙了,没时间更新示例脚本):

self.driver.swipe(start_x=location['x'], start_y=location['y'], end_x=0.5, end_y=location['y'], duration=0.8)

接着再运行,Python 就会报出 WebDriverException: Message: u'An error occurred while executing user supplied JavaScript.' 的错误,但没有更详细的错误信息。
此时我们可以打开 Appium 控制台,就可以看到下面的 Log 信息:
info: [INST] 2014-05-30 07:30:06 +0000 Debug: target.dragFromToForDuration({x:"35", y:"83"}, {x:"160", y:"83"}, "0.0008")

info: [INST] 2014-05-30 07:30:06 +0000 Debug: duration value must be greater than or equal to 0.5 or less than 60

info: [INSTSERVER] Socket data received (116 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Got result from instruments: {"status":17,"value":"duration value must be greater than or equal to 0.5 or less than 60"}
info: Responding to client with error: {"status":17,"value":{"message":"An error occurred while executing user supplied JavaScript.","origValue":"duration value must be greater than or equal to 0.5 or less than 60"},"sessionId":"e388a747-8c9c-4df8-bf6d-2fdf5660ee6c"}

其中关键的是 “duration value must be greater than or equal to 0.5 or less than 60 ” 这句话,意思是说 “持续时间值必须大于或等于 0.5,或小于 60”,但我们设置的 duration 值已经是 0.8 了,为什么还会失败呢?原来设置的值传到 instruments 后被乘以了 0.001(毫秒转换为秒了),但 instruments 要求 duration 值最小为 0.5.
好了,我们按照提示,把这段代码改为(duration 值改为 2000,此处的值只要符合乘以 0.001 后大于等于 0.5 小于 60 即可):

def test_scroll(self):
        els = self.driver.find_elements_by_class_name('UIAButton')
        els[3].click()

        sleep(1)
        el = self.driver.find_element_by_name('OK')
        el.click()

        sleep(1)
        el = self.driver.find_element_by_xpath('//UIAMapView[1]')

        location = el.location
        self.driver.swipe(start_x=location['x'], start_y=location['y'], end_x=0.5, end_y=location['y'], duration=2000)

此时传到 instruments 的 duration 值就会变为 2,结果就可以成功运行并实现滑动效果了。


↙↙↙阅读原文可查看相关链接,并与作者交流