UI自动化的基本流程:
1、打开浏览器
2、打开网页
3、定位元素
4、操作元素
5、断言是否成功
以下将整个流程模块化
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
url = "https://www.baidu.com/"
login_text = "登录"
account = "admin"
pwd = "123456"
def get_ele_times(driver, times, func):
return WebDriverWait(driver, times).until(func)
# 打开浏览器封装
def openBrower():
driver = webdriver.Chrome()
return driver
# 打开网址封装
def openUrl(driver, url):
driver.get(url)
driver.maximize_window()
# 定位元素封装
def findElement(d, arg):
if "text_id" in arg:
ele_login = get_ele_times(d, 10, lambda d: d.find_element_by_link_text(arg["text_id"]))
ele_login.click()
time.sleep(3)
useEle = d.find_element_by_id(arg["userid"])
pwdEle = d.find_element_by_id(arg["pwdid"])
loginEle = d.find_element_by_id(arg["loginid"])
return useEle, pwdEle, loginEle
# 发送数据封装
def sendVals(eletuple, arg):
listkey = ["uname", "pwd"]
i = 0
for key in listkey:
eletuple[i].send_keys("")
eletuple[i].clear()
eletuple[i].send_keys(arg[key])
i += 1
eletuple[2].click()
# 检验结果封装
def checkResult(d, text):
try:
d.find_element_by_link_text(text)
print("Account And Pwd Right")
except:
print("Account And Pwd Error")
# 测试用例
def test_login():
# 1、打开浏览器
d = openBrower()
# 2、打开网页
openUrl(d, url)
ele_dict = {
"text_id": login_text,
"userid": "TANGRAM__PSP_11__userName",
"pwdid": "TANGRAM__PSP_11__password",
"loginid": "TANGRAM__PSP_11__submit"
}
account_dict = {
"uname": account,
"pwd": pwd
}
# 定位元素
ele_tuple = findElement(d, ele_dict)
# 输入输入框的值
sendVals(ele_tuple, account_dict)
# 检验是否登录成功
checkResult(d, "找回密码")
if __name__ == '__main__':
test_login()