1. 程式人生 > >Appium 新手貼:Windows 平臺上的使用 Python 語言實現 appium 自動化程式 for Android (完整版)

Appium 新手貼:Windows 平臺上的使用 Python 語言實現 appium 自動化程式 for Android (完整版)

https://testerhome.com/topics/646

前面寫了個《新手貼: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("[email protected]")

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

driver.quit()

4)執行CMD,進入python目錄,輸入命令python android_contact.py 此時會自動安裝apk並完成相應的新增聯絡人的操作

OK整個配置執行就算完成了

21 個贊 共收到 34 條回覆 672

@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

672

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("[email protected]")

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

654

回答3樓的問題 :
desired_caps['version'] = '4.1.2'
真機系統版本要>=4.2...

672

@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

96

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')"

96

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'

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("[email protected]")

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

driver.quit()

96
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("[email protected]")

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

driver.quit()


96

請問樓主,下載ContactManager.apk所需要的密碼是多少?

743

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

96

加這個群156413673,群共享有ContactManager.apk

773

Parameter 'appPackage' is required for launching application怎麼解決?

786

樓主你好!用程式碼編譯後,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'

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("[email protected]")

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

858

當我用tag_name定位輸入框的時候:textfields = driver.find_elements_by_tag_name("textfield")
為什麼會提示定位錯誤呢?
錯誤資訊:selenium.common.exceptions.WebDriverException: Message: u'Invalid locator strate gy: tag name‘
用xpath定位的時候,出現和樓上仁兄一樣的問題,打印出來是空的!

858

我這邊發現問題了,使用1.0版本的,會出現上述情況,使用0.14版本的,可以用tag name定位,奇怪了,1.0版本的怎麼用呢?希望有高手回答下!多謝

903

from selenium import webdriver
from appium import webdriver兩種方式有什麼區別嗎?

96

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

如果不需要安裝,直接執行機器裡已經安裝好的應用,要怎麼處理?

2296

請問下:執行以後出現:
raise URLError(err)
urllib2.URLError:
這個哪裡出了問題呀,請指教

648
二python+selenium安裝配置 第五步一直不行,求解啊 1537
  • -樓主 我已安裝py3,然後按照你的步驟來 cmd 命令npm 來安裝appium 報錯,說不支援python3....有何解決方案呢...
96

樓主大大,這個apk怎麼下載,雲盤不能用了。可以給新地址不,謝謝

4341

APK地址找不到了,能否重新提供一個?新手來混論壇,多多關照!

3187

[debug] [MJSONWP] Bad parameters: BadParametersError: Parameters were incorrect. We wanted {"required":["value"]} and you sent ["text","sessionId","id","value"]
請教下,執行之後報這個錯誤,不知道什麼原因