![f6a53f7208233d503fd5304847c6e5ff.png](https://i-blog.csdnimg.cn/blog_migrate/194c49c0886bf8f1b3c5a6aff1c0c692.jpeg)
本文为主要帮助会写基本selenium测试代码又没有规划的同仁。
本文应用到POM模型、selenium、unittest框架、configparser配置文件、smtplib邮件发送、HTMLTestRunner测试报告模块结合登录案例实现简单自动化测试框架
项目主要包括以下几个部分
![cf9bb93910a95d1e061f50003db17d97.png](https://i-blog.csdnimg.cn/blog_migrate/0691e9cefd4422b76f9cb3baef9b16e2.png)
conif.ini 放置配置文件
例如:
![b218d57ad01da835e053c5f7ad4e545e.png](https://i-blog.csdnimg.cn/blog_migrate/e35761a6c289dfbdd1e5b01f53318cdc.png)
myunit.py文件放置的浏览器操作代码
import unittest
from selenium import webdriver
class MyTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
def tearDown(self):
self.driver.quit()
if __name__=='__main__':
unittest.main()
base.py中放置浏览器对象操作代码
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import os,configparser
class Page(object):
path = os.path.dirname(os.path.abspath("."))
cfpath = os.path.join(path, 'autoparkerconfigconf.ini')
conf = configparser.ConfigParser()
conf.read(cfpath)
url=conf.get('base','url')
def __init__(self,driver,url=url):
self.driver=driver
self.url=url
def open(self):
self.driver.get(self.url)
def find_element(self,*loc):#传入参数为元组需要加*,本身就是元组的不需要*
#print(*loc)
try:
WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))
return self.driver.find_element(*loc)
except:
print('页面中未找到 %s 元素'%(self,loc))
def find_elements(self,*loc):
return self.driver.find_elements(*loc)
def send_keys(self,loc,value):
self.find_element(*loc).send_keys(value)
def click(self,loc):
self.find_element(*loc).click()
def clear(self,loc):
self.find_element(*loc).clear()
loginpage.py中放置通用登录模块代码(尽量避免重复代码)
from selenium.webdriver.common.by import By
from time import sleep
from objpage.base import Page
class login(Page):
username_loc=(By.NAME,'accounts')
password_loc=(By.NAME,'pwd')
login_button_loc=(By.XPATH,'/html/body/div[5]/div/form/fieldset/p/button')
login_error_loc=(By.XPATH,'//*[@id="common-prompt"]/p')
def login_username(self,username):
self.find_element(*self.username_loc).clear()
self.find_element(*self.username_loc).send_keys(username)
def login_password(self,password):
self.find_element(*self.password_loc).clear()
self.find_element(*self.password_loc).send_keys(password)
def login_button(self):
self.find_element(*self.login_button_loc).click()
#统一登录入口
def user_login(self,username,password):
self.open()
self.login_username(username)
self.login_password(password)
self.login_button()
sleep(2)
#登录提示信息
def login_error_text(self):
return self.find_element(*self.login_error_loc).text
parker.py中放置公共元素操作代码(parker是我随便命名的,不纠结)
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
class Parker(object):
def __init__(self,browser='chrome'):
if browser=='ie' or browser=='internet explorer':
driver=webdriver.Ie()
elif browser=='firefox' or browser=='ff':
driver=webdriver.Firefox()
elif browser=='chrome':
driver=webdriver.Chrome()
try:
self.driver=driver
except Exception:
raise NameError('没有找到浏览器,请输入"ie","chrome","ff"')
def wait(self,secs=5): #隐式等待
self.driver.implicitly_wait(secs)
def to_element(self,key):#元素定位
if '->' not in key: #如果key里面不包含=就执行下列语句
raise NameError('参数类型输入错误')
by=key.split('->')[0] #通过分隔获取[0]对应的值
val=key.split('->')[1]#通过分隔获取[1]对应的值
if by=='id':
element=self.driver.find_element_by_id(val)
elif by=='name':
element=self.driver.find_element_by_name(val)
elif by=='class':
element=self.driver.find_element_by_class_name(val)
elif by=='link_text':
element=self.driver.find_element_by_link_text(val)
elif by=='xpath':
element=self.driver.find_element_by_xpath(val)
elif by=='css':
element=self.driver.find_element_by_css_selector(val)
else:
raise NameError('请输入正确的定位方式:id,name,class,link_text,xpath,css')
return element
def open(self,url):#打开一个URL
self.driver.get(url)
def max_window(self):#最大化窗口(浏览器)
self.driver.maximize_window()
def set_windows(self,wide,high):#设置窗口大小
self.driver.set_window_size(wide,high)
def input(self,key,text):#对文本框进行输入
el=self.to_element(key)
el.send_keys(text)
def click(self,key):#点击
el=self.to_element(key)
el.click()
def clear(self,key):#清除文本框内容
el=self.to_element(key)
el.clear()
def right_click(self,key):#右键操作
el=self.to_element(key)
ActionChains(self.driver).context_click(el).perform()
def move_to_element(self,key):#鼠标悬停
el=self.to_element(key)
ActionChains(self.driver).move_to_element(el).perform()
def drag_and_drop(self,el_key,ta_key):#拖拽 从一个元素拖到另外一个元素
el=self.to_element(el_key)
target=self.to_element(ta_key)
ActionChains(self.driver).drag_and_drop(el,target).perform()
def click_text(self,text):
self.driver.find_element_by_partial_link_text(text).click()
def close(self):#关闭当前浏览器窗口
self.driver.close()
def quit(self):#退出浏览器
self.driver.quit()
def submit(self,key):#提交事件
el=self.to_element(key)
el.submit()
def F5(self):#刷新
self.driver.refresh()
def js(self,script):#执行js
self.driver.execute_script(script)
def get_attribute(self,key,attribute):#获取元素属性
el=self.to_element(key)
return el.get_attribute(attribute)
def get_text(self,key):#获取text
el=self.to_element(key)
return el.text
def get_title(self):#获取title
return self.driver.title
def get_url(self):#获取url
return self.driver.current_url
def to_frame(self,key):#窗口切换
el=self.to_element(key)
self.driver.switch_to.frame(el)
def alert_accept(self):#对话框确认操作
self.driver.switch_to.alert.accept()
def alert_dismiss(self):#对话框取消操作
self.driver.switch_to.alert.dismiss()
def img(self,fp):#截图
self.driver.get_screenshot_as_file(fp)
def select_by_value(self,key,value):#下拉框操作
el=self.to_element(key)
Select(el).select_by_value(value)
send_email.py放置邮件发送代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import configparser
import os
def sendEmail(file_path):
path=os.path.dirname(os.path.abspath("."))
cfpath=os.path.join(path,'autoparkerconfigconf.ini')
conf = configparser.ConfigParser()
conf.read(cfpath)
smtpserver = conf.get('emailqq','smtpserver')
sender = conf.get('emailqq','sender')
pwd = conf.get('emailqq','pwd')
receiver=[]
email_to=conf.get('emailqq','receiver')
email_array=email_to.split(';')
for i in range(len(email_array)):
receiver.append(email_array[i])
print(receiver)
with open(file_path,'rb') as fp:
mail_boby=fp.read()
msg=MIMEMultipart()
msg['From']=sender
msg['To']=",".join(receiver)
msg['Subject']='我曾把完整的镜子打碎'
body=MIMEText(mail_boby,'html','utf-8')
msg.attach(body)
att=MIMEText(mail_boby,'html','utf-8')
att['Content-Type']='application/octet-stream'
att['Content-Disposition']='attachment;filename="test_reuslt.html"'
msg.attach(att)
try:
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender,pwd)
except:
smtp=smtplib.SMTP_SSL(smtpserver,465)
smtp.login(sender,pwd)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
sendEmail('D:report.html')
最后main.py文件放置的就是运行代码(执行这个文件进行测试就可以)
import HTMLTestRunner
import unittest
from test_case.login import loginTest
from public.send_email import sendEmail
if __name__=='__main__':
testunit=unittest.TestLoader().loadTestsFromTestCase(loginTest)
suite=unittest.TestSuite(testunit)
file_path="D:html_report.html"
fp=open(file_path,'wb')
runner=HTMLTestRunner.HTMLTestRunner(stream=fp,title='登录测试',description='测试执行结果')
runner.run(suite)
fp.close()
sendEmail(file_path)
收藏关注+点赞~养成好习惯~