2. AppiumDriver getPageSource
  AppiumDriver(Client) 可以很方便的获得当前正在运行的 Activity 的 UI 描述,随后可根据返回的 XML 文档来寻找元素。

  确定元素位置后,即可根据前述的 Find 方法来查找/选择元素
  编写完整的测试代码
  正确的获取元素之后便可以获取元素相关的信息,随后使用各语言常用的测试框架编写测试即可,如 Java 的 JUnit,Nodejs 的 Mocha 等。
  这里我使用 Appium 主要是为了模拟用户点击添加微信好友,所以完整的程序并没有使用到测试框架。相关的 UI 元素获取/操作方法供大家参考。
# coding:utf-8
from appium import webdriver
from time import sleep
def addFriend(dr, id, dryRun=False):
succ = False
wechatId = str(id)
dr.find_element_by_accessibility_id(r"更多功能按钮").click()
item_list = dr.find_elements_by_class_name("android.widget.LinearLayout")
try:
item_list[2].click()
except:
print "Error! in item list len"
return succ
el = dr.find_element_by_class_name("android.widget.ListView")
item_list = el.find_elements_by_class_name("android.widget.LinearLayout")
try:
item_list[1].click()
except:
print "Error! in item list len"
return succ
t = dr.find_element_by_id("com.tencent.mm:id/f7")
t.send_keys(wechatId)
search = dr.find_element_by_id("com.tencent.mm:id/aqw")
.find_element_by_class_name("android.widget.RelativeLayout")
search.click()
try:
freq = dr.find_element_by_id('com.tencent.mm:id/aqq')
assert freq.text == u"操作过于频繁,请稍后再试。"
print "Frequency too high! Sleep 300s"
sleep(60)
return succ
except:
pass
try:
dr.find_element_by_id('com.tencent.mm:id/a8x').click()
addBtn = dr.find_element_by_id('com.tencent.mm:id/eu')
if not dryRun:
addBtn.click()
succ = True
print "Success Send Requests:" + wechatId
except:
print "No Such User Or Already a Friend:" + wechatId
while True:
try:
dr.find_element_by_id('com.tencent.mm:id/fb').click()
except:
try:
dr.find_element_by_id('com.tencent.mm:id/f4').click()
except:
break
return True
def resetActivity(dr, desired_caps):
dr.start_activity(desired_caps['appPackage'], desired_caps['appActivity'])
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'm3_note'
desired_caps['appPackage'] = 'com.tencent.mm'
desired_caps['appActivity'] = '.ui.LauncherUI'
print "Trying connect to phone..."
dr = {}
try:
dr = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
except Exception, e:
print "Cannot Connect to phone :", e
exit()
print "Successfully connect to phone."
print "Reading friend list..."
friendList = []
fp = open("friends.txt")
line = fp.readline().strip()
while line:
friendList.append(line)
line = fp.readline().strip()
print "Finish reading friends. Total: " + str(len(friendList))
print "Wait for Wechat's splash screen...."
for i in range(0, 10):
print 10 - i
sleep(1)
succ_list = []
fail_list = []
for i in friendList:
try:
succ = addFriend(dr, i, dryRun=False)
if succ:
succ_list.append(i)
else:
fail_list.append(i)
except:
fail_list.append(i)
resetActivity(dr, desired_caps)
print "Succeed List:"
print " ".join(succ_list)
print "Failed List:"
print " ".join(fail_list)
dr.close()