Appium 新手贴:Windows 平台上的使用 Python 语言实现 appium 自动化程序 for Android (完整版)

Mr Wang · 2014年04月02日 · 最后由 moonlight 回复于 2018年12月23日 · 5176 次阅读
本帖已被设为精华帖!

前面写了个《新手贴:Windows 平台上的使用 Java 语言实现 appium 自动化程序 for Android(完整版)》的帖子:http://testerhome.com/topics/645 ,针对 python 语言 也来看看如何实现。还是按照流水账的形式来描述。

一,环境配置篇
在 Windows 上配置
1)下载安装 node.js(http://nodejs.org/download/)安装的时候有选项,记得把环境变量添加到 path 路径
2)使用 npm 安装 appium,运行 CMD 输入 npm install -g appium(有些朋友反应在 cmd 下运行 npm 无效,如果这样请把 nodejs 的目录添加到用户变量的 path 下重启 cmd 即可 参考帖子:http://blog.csdn.net/iispring/article/details/8023319),如下图:

3)下载安装 Android SDK(http://developer.android.com/sdk/index.htmlANDROID_HOMESDK 路径,PATH 变量设定%),设置环境变量指向 ANDROID_HOME%\tools 和% ANDROID_HOME%\platform-tools
4)安装 JDK 并设置 JAVA_HOME 环境变量
5)安装 ANT,并将%ANT_HOME%\bin 路径加到 PATH
6)安装 MAVEN,设置%M2_HOME%\bin,并添加到 PATH 中
7)安装 Git
8)运行 CMD 输入 appium-doctor 检查你的环境是不是都配置好了 如图:

整体的环境变量已经配置完毕,不过接下来要配置 python+selenium 安装。

二,python+selenium 安装配置:
1)下载并安装 python 去这个地址http://www.python.org/27 的 python 版本,发表文章时,我使用的是
2)下载并安装 setuptools【这个工具是 python 的基础包工具】
去这个地址https://pypi.python.org/packages/2.7/s/setuptools/setuptools,对应 python 了 2.7 的版下载
3)去这个地址http://pypi.python.org/pypi/pippip,将 pip 用 WINRAR 解压到某盘根目录下,我的解压目录为 c:\pip下载
4)使用 CMD 命令进入以上解压后的文件夹 c:\pip,然后使用 python setup.py install
a、如果 python 命令使用不成功,请配置下环境变量 就能 OK(这个去百度一下吧。。。。)
b、报错 no module named setuptools 可以下载一个运行 ez_setup.py,运行 ez_setup.py:python ez_setup.py ;
如果运行正常,那就安装成功了。)
参考图 (运行结果不保证与该图完全一致):

5)再打开 CMD 命令,进入 python 的 script 路径,如本人的 C:\Python\Scripts 然后输入 命令:easy_install pip(恭喜你这边安装成功后,就可以顺利使用 pip 命令了)
参考图 (运行结果不保证与该图完全一致):

6)直接使用 pip 安装 selenium,命令为:pip install selenium -i http://pypi.douban.com/simple(使用国内地址)
参考图 (运行结果不保证与该图完全一致):

7)打开 python 的 shell 或者 IDEL 界面 ,输入 from selenium import webdriver 如果不报错那就说明你已经安装 selenium for python 成功了。
安装过程也可以参考:http://rubygems.org/gems/selenium-webdriver

三,appium 启动篇
由于我测试是连接真机的,所以这里需要先通过 adb devices -l 命令获得 真机的 udid 号,详细步骤如下:
1)真机(安卓版本 4.2.2)通过 USB 连接 电脑,驱动装好,打开 USB 调试模式
2)再在 cmd 中输入 appium -a 127.0.0.1 -p 4723 (-a 表示 ip,-p 表示端口, 可以通过 appium -h 查看更多命令)
3)如果如下图所示 就表示 appium 服务启动成功了,注意这个窗口不要关闭 因为这是 appium 的服务 关了就关了服务,后面过程无法执行,而且这个窗口也是 日志输出的窗口用于排错。

四,代码执行篇
这块我主要是执行的是官方的演示代码:通讯录管理 app,安装打开 app,并添加一个联系人保存的操作
1)首先去下载 ContactManager.apk(http://yunpan.cn/QInSWzP2YWgTJ
2)将官网的示例代码 android_contact.py 下载下来 放在 Python 的目录
3)对 python 代码进行部分修改

import os
from selenium import webdriver

# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

desired_caps = {}
desired_caps['device'] = 'Android'
desired_caps['browserName'] = ''
desired_caps['version'] = '4.2.2'
desired_caps['app'] = PATH('C:\Users\Stephen\Desktop\ContactManager.apk')
desired_caps['app-package'] = 'com.example.android.contactmanager'
desired_caps['app-activity'] = '.ContactManager'

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

el = driver.find_element_by_name("Add Contact")
el.click()

textfields = driver.find_elements_by_tag_name("textfield")
textfields[0].send_keys("My Name")
textfields[2].send_keys("someone@somewhere.com")

driver.find_element_by_name("Save").click()

driver.quit()

4)运行 CMD,进入 python 目录,输入命令 python android_contact.py 此时会自动安装 apk 并完成相应的添加联系人的操作

OK 整个配置执行就算完成了

共收到 35 条回复 时间 点赞

请问下:运行以后出现:
raise URLError(err)
urllib2.URLError:
这个哪里出了问题呀,请指教

[debug] [MJSONWP] Bad parameters: BadParametersError: Parameters were incorrect. We wanted {"required":["value"]} and you sent ["text","sessionId","id","value"]
请教下,运行之后报这个错误,不知道什么原因

好帖,好贡献

顶一下好帖···
来一个 nodejs 版本的楼主··

@young 最后一步运行 CMD,进入 python 目录,输入命令 python android_contact.py 此时会自动安装 apk 并完成相应的添加联系人的操作
我提示报错,请大侠帮忙看看是为何?
C:\Python27\Scripts>python C:\Python27\Scripts\android_contact.py Traceback (most recent call last): File "C:\Python27\Scripts\android_contact.py", line 17, in driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 72, in init self.start_session(desired_capabilities, browser_profile) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 115, in start_session 'desiredCapabilities': desired_capabilities, File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 164, in execute response = self.command_executor.execute(driver_command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 347, in execute return self._request(command_info[0], url, body=data) File "C:\Python27\lib\site packages\selenium\webdriver\remote\remote_connection.py", line 429, in _request body = data.decode('utf-8').replace('\x00', '').strip() File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xb4 in position 193: invalid start byte

python android_contact.py 的代码如下:
import os
from selenium import webdriver
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(file), p)
)

desired_caps = {}
desired_caps['device'] = 'android'#android selendroid
desired_caps['browserName'] = ''
desired_caps['version'] = '4.1.2'
desired_caps['app'] = PATH('D:\test\ContactManager.apk')
desired_caps['app-package'] = 'com.example.android.contactmanager'
desired_caps['app-activity'] = '.ContactManager'
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

el = driver.find_element_by_name("Add Contact")
el.click()

textfields = driver.find_elements_by_tag_name("textfield")
textfields[0].send_keys("My Name")
textfields[2].send_keys("someone@somewhere.com")

driver.find_element_by_name("Save").click()
driver.quit()

回答 3 楼的问题 :
desired_caps['version'] = '4.1.2'
真机系统版本要>=4.2...

可行~~已跑上。

@young 全部按要求配置完成,运行 android_contact.py 报如下错误,请大侠帮忙看看?谢谢!
C:\Users\cylboy>python D:\test\android_contact.py
Traceback (most recent call last):
File "D:\test\android_contact.py", line 17, in
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 72, in init
self.start_session(desired_capabilities, browser_profile)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 115, in start_session
'desiredCapabilities': desired_capabilities,
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 164, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\remote_connectio
n.py", line 347, in execute
return self._request(command_info[0], url, body=data)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\remote_connectio
n.py", line 429, in _request
body = data.decode('utf-8').replace('\x00', '').strip()
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb4 in position 193: invalid
start byte

#8 楼 @cylboy 你不贴个代码 真很难帮你。

Traceback (most recent call last):
File "C:\android_contact.py", line 17, in
driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 71, in init
self.start_session(desired_capabilities, browser_profile)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 113, in start_session
'desiredCapabilities': desired_capabilities,
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 164, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: u"A new session could not be created. (Original error: Bad app: C:\C:\test\ContactManager.apk. App paths need to be absolute, or relative to the appium server install dir, or a URL to compressed file, or a special app name. cause: Error: Error locating the app: ENOENT, stat 'C:\C:\test\ContactManager.apk')"

import os
from selenium import webdriver

Returns abs path relative to this file and not cwd

PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(file), p)
)

desired_caps = {}
desired_caps['device'] = 'Android'
desired_caps['browserName'] = ''
desired_caps['version'] = '4.2.2'
desired_caps['app'] = PATH('C:\test\ContactManager.apk')
desired_caps['app-package'] = 'com.example.android.contactmanager'
desired_caps['app-activity'] = '.ContactManager'

driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

el = driver.find_element_by_name("Add Contact")
el.click()

textfields = driver.find_elements_by_tag_name("textfield")
textfields[0].send_keys("My Name")
textfields[2].send_keys("someone@somewhere.com")

driver.find_element_by_name("Save").click()

driver.quit()

不知道怎么弄了~

根据你的教程做的~

import os
from selenium import webdriver

# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

desired_caps = {}
desired_caps['device'] = 'Android'
desired_caps['browserName'] = ''
desired_caps['version'] = '4.2.2'
desired_caps['app'] = PATH('C:\test\ContactManager.apk')
desired_caps['app-package'] = 'com.example.android.contactmanager'
desired_caps['app-activity'] = '.ContactManager'

driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

el = driver.find_element_by_name("Add Contact")
el.click()

textfields = driver.find_elements_by_tag_name("textfield")
textfields[0].send_keys("My Name")
textfields[2].send_keys("someone@somewhere.com")

driver.find_element_by_name("Save").click()

driver.quit()


请问楼主,下载 ContactManager.apk 所需要的密码是多少?

加这个群 156413673,群共享有 ContactManager.apk

Parameter 'appPackage' is required for launching application 怎么解决?

#19 楼 @scott

http://testerhome.com/topics/729

可以参考这个。是版本的问题

楼主你好!用代码编译后,textfields[0].send_keys("My Name") 报 index:error,请问怎么解决呀?试过很多方法了,自行解决不了,谢谢
import os
from selenium import webdriver

Returns abs path relative to this file and not cwd

PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(file), p)
)

desired_caps = {}
desired_caps['device'] = 'Android'
desired_caps['browserName'] = ''
desired_caps['version'] = '4.2.2'
desired_caps['app'] = PATH('C:\Users\Succi\Desktop\ContactManager.apk')
desired_caps['app-package'] = 'com.example.android.contactmanager'
desired_caps['app-activity'] = '.ContactManager'

driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

el = driver.find_element_by_name("Add Contact")
el.click()

textfields = driver.find_elements_by_tag_name("textfield")
print("debug:",textfields)#input list
textfields[0].send_keys("My Name")
textfields[2].send_keys("someone@somewhere.com")

driver.find_element_by_name("Save").click()

driver.quit()

错误信息:
('debug:', [])
Traceback (most recent call last):
File "android_contact.py", line 24, in
textfields[1].send_keys("My Name")
IndexError: list index out of range

当我用 tag_name 定位输入框的时候:textfields = driver.find_elements_by_tag_name("textfield")
为什么会提示定位错误呢?
错误信息:selenium.common.exceptions.WebDriverException: Message: u'Invalid locator strate gy: tag name‘
用 xpath 定位的时候,出现和楼上仁兄一样的问题,打印出来是空的!

我这边发现问题了,使用 1.0 版本的,会出现上述情况,使用 0.14 版本的,可以用 tag name 定位,奇怪了,1.0 版本的怎么用呢?希望有高手回答下!多谢

二 python+selenium 安装配置:第 2、3、4 步可以简化成下面一步到位
进入https://pypi.python.org/pypi/setuptools/#windows-7-or-graphical-install 直接下载 ez_setup.py 双击运行即可。安装成功后会发现在 Python 目录多了 script 文件夹。然后进入 第 5 步

from selenium import webdriver
from appium import webdriver 两种方式有什么区别吗?

desired_caps['app'] = PATH('C:\Users\Stephen\Desktop\ContactManager.apk')
是必须的吗?

如果不需要安装,直接运行机器里已经安装好的应用,要怎么处理?


二 python+selenium 安装配置 第五步一直不行,求解啊

  • -楼主 我已安装 py3,然后按照你的步骤来 cmd 命令 npm 来安装 appium 报错,说不支持 python3....有何解决方案呢...

楼主大大,这个 apk 怎么下载,云盘不能用了。可以给新地址不,谢谢

APK 地址找不到了,能否重新提供一个?新手来混论坛,多多关照!

莫等闲 使用 Python 运行 Appium 测试的示例 中提及了此贴 03月19日 18:42
耿纪坤 回复

同样的错误请问怎样解决的?driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) 这个东西是干嘛的?

@jikunsishen 我也遇到了 selenium.common.exceptions.WebDriverException: Message: u"A new session could not be created. (Original error: Parameter 'appPackage' is required for launching application)"

mark 一下。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册