实战项目

均来源于互联网

测试报告2017年11月29日优化后的测试报告:https://github.com/defnngj/HTMLTestRunner

1、项目概述:

本实战已126邮箱为例子进行了实战,对登录、写邮件、发送邮件、删除邮件、退出登录进行了自动化测试;

测试完成后自动发送测试报告到指定邮箱

目录结构:

auto_working目录:

report                         ---> 目录用于存放测试报告

test_case                    ---> 存放测试用例目录,该目录下面创建测试用例:test_asendmail.py 写发送邮件 ;  test_bserach.py 搜索邮件 ; test_cdel.py 删除邮件 ; login.py 登录

HTMLTestRunner.py   ---> 自动生成测试报告

all_test.py                   ---> 运行测试用例

  all_test.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
import unittest
from HTMLTestRunner import HTMLTestRunner
import time,os # 定义发送邮件 def send_mail(file_new):
'''发送邮件''' SMTP_host = 'smtp.126.com'
#发信邮箱账号
username = 'test_tx@126.com'
#发信密码一定要126开启smtp发给的密码,不是126登录的密码
password = 'xxxxxxxxxxxxx'
#收件邮箱
to_address = 'xxxxoooo@qq.com'
#邮件标题
subject = 'UI自动化测试报告'
#连接SMTP服务器,此处用126的SMTP服务器
email_client = SMTP(SMTP_host)
#用户名和密码登录
email_client.login(username,password) f = open(file_new,'rb')
read = f.read()
f.close() msg = MIMEText(read,_subtype='hmtl',_charset='utf-8')
msg['Subject'] = Header(subject,'utf-8') #邮件主题
msg['From'] = username #定义发送邮件人邮箱
msg['To'] = to_address #定义收邮件人邮箱
email_client.sendmail(username,to_address,msg.as_string(msg))#第一个参数发送人邮箱,第二个参数为收件人邮箱,第三个为发送内容
email_client.quit() #退出 def send_report(testreport):
'''生成报告'''
result_dir = testreport
lists = os.listdir(result_dir) #获取该目录下面的所有文件
lists.sort(key= lambda fn:os.path.getatime(result_dir+"\\"+fn))
#找到最新生成的文件
file_new = os.path.join(result_dir,lists[-1])
#调用发邮件模块
send_mail(file_new) def creatsuite():
'''将用例添加到测试套件'''
testunit = unittest.TestSuite()
#定义测试文件查找的目录
test_dir ='./test_case'
#定义discover方法的参数
discover = unittest.defaultTestLoader.discover(test_dir,pattern='test_*.py',top_level_dir=None)
#discover方法筛选出来的用例,循环添加到测试套件中 return discover if __name__ == '__main__': now = time.strftime("%Y-%m-%d %H-%M-%S")
testreport = './report'
filename ='./report/ {0} result.html'.format(now)
fp = open(filename,'wb')
runner = HTMLTestRunner(stream=fp,title="2017年7月18日ui自动化测试报告",description="运行环境 Windows7 Chrome浏览器")
alltestnames = creatsuite()
runner.run(alltestnames)
fp.close() #关闭生成的报告
send_report(testreport) #发送报告

 test_case目录下面的测试用例:

 login.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian #登录 from selenium import webdriver
import time class Login_Case: def __init__(self,driver):
self.driver = driver def login_curres(self,user,passwd):
'''登录成功'''
self.driver.switch_to_frame("x-URS-iframe")
self.by_id("//input[@name='email']").clear()
self.by_id("//input[@name='email']").send_keys(user)
self.by_id("//input[@name='password']").clear()
self.by_id("//input[@name='password']").send_keys(passwd)
self.by_id(".//*[@id='dologin']").click()
return self.driver def logout(self):
'''退出登录'''
self.by_id(".//*[@id='_mail_component_41_41']/a").click() def by_id(self,the_id):
return self.driver.find_element_by_xpath(the_id)

 test_asendmail.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian import unittest
from selenium import webdriver
from time import sleep
from login import Login_Case class Test_Send_Mail(unittest.TestCase):
driver = webdriver.Chrome()
@classmethod
def setUpClass(cls):
cls.driver.maximize_window()
base_url = "http://mail.126.com/"
cls.driver.get(base_url)
# cls.driver.implicitly_wait(10)
sleep(10) def obj_metcho(self):
obj = Login_Case(Test_Send_Mail.driver)
return obj def test_alogin_surcee(self):
'''登录进入123邮箱'''
username ='test_tx'
password = "xxxxxxxx"
login_obj = self.obj_metcho() title = self.driver.title
print("登录前title:{0}".format(title))
url = self.driver.current_url
print("登录前url:{0}".format(url)) driver = login_obj.login_curres(username,password)
driver.switch_to_default_content()
sleep(5)
url = self.driver.current_url
print("登录成功后url:{0}".format(url))
print("登录成功后的title:{0}".format(self.driver.title))
self.result = self.by_id("//span[@id='spnUid']").text
self.assertTrue(username in self.result) def test_bwrite(self):
'''写邮件输入收件人、主题、正文'''
driver = self.driver
#点击左上角的写信按钮
self.by_id("//*[@id='dvNavTop']/ul/li[2]/span[2]").click()
sleep(5) #输入收件人email地址
self.by_id("//*[@role='combobox']").send_keys("352932341@qq.com")
sleep(5) #选中主题文本,输入主题内容;
self.by_id("//input[@class='nui-ipt-input' and @type='text' and @maxlength='256']").click()
self.by_id("//input[@class='nui-ipt-input' and @type='text' and @maxlength='256']").send_keys("我是自动化测试发邮件给你的啊") #主题第二种定位方式
# self.by_id(".//*[@class='bz0']/div[1]/input[@class='nui-ipt-input']").click()
# self.by_id(".//*[@class='bz0']/div[1]/input[@class='nui-ipt-input']").send_keys("我是自动化发给你的邮件谢谢你光临")
sleep(5)
#定位到正文iframe中
class_name = self.by_id("//*[@class='APP-editor-iframe']")
driver.switch_to_frame(class_name)
driver.find_element_by_tag_name("body").send_keys("hi,all 各位小伙伴本次ui自动化测试通过了")
# .//*[@class='jp0']/div[1]/span[2]
driver.switch_to_default_content()
self.by_id("//*[@class='jp0']/div[1]/span[2]").click()
sleep(10)
text = self.by_id("//*[@class='tK1' and @role='tooltip']").text
self.assertIn(text, "发送成功可用手机接收回复免费短信通知") def test_csend_mail(self):
'''只填写收件人发送邮件''' #点击继续写信
self.by_id("//*[@class='py1']/a[3]").click()
#输入收件人邮箱
self.by_id("//*[@class='bz0']/div[2]/div[1]/input").send_keys("352932341@qq.com")
sleep(5)
#点击发送按钮
self.by_id("//*[@class='jp0']/div[1]/span[2]").click()
sleep(5)
#确定不输入主题和正文的弹窗
self.by_id("//*[@class='nui-msgbox-ft-btns']/div[1]/span").click()
sleep(5)
text =self.by_id("//*[@class='sQ1']/h1").text
self.assertIn("发送成功",text) def test_dsend_mail(self):
'''只填写收件人与主题发送'''
self.by_id("//*[@class='py1']/a[3]").click() #点击继续写信
# self.by_id("//*[@id='dvNavTop']/ul/li[2]/span[2]").click() #直接登录后,点击写信
#输入收件人邮箱
self.by_id("//*[@class='bz0']/div[2]/div/input").send_keys("352932341@qq.com")
sleep(5)
#输入主题
self.by_id("//*[@class='nui-ipt-input' and @maxlength='256']").click()
self.by_id("//*[@class='nui-ipt-input' and @maxlength='256']").send_keys("我只输入的主题没有输入正文")
sleep(5)
#点击发送按钮
self.by_id("//*[@class='jp0']/div[1]/span[2]").click()
sleep(5)
#获取发送成功后的文本信息
text = self.by_id("//*[@class='sQ1']/h1").text
self.assertIn("发送成功",text) def test_esend_mail(self):
'''输入收件人、主题、附件'''
self.by_id("//*[@class='py1']/a[3]").click() #点击继续写信
#下面代码是,重新登录进入的
# self.by_id("//*[@id='dvNavTop']/ul/li[2]/span[2]").click()
#输入收件人邮箱
sleep(5)
self.by_id("//*[@class='bz0']/div[2]/div/input").send_keys("352932341@qq.com")
sleep(5)
#输入主题
self.by_id("//*[@class='nui-ipt-input' and @maxlength='256']").click()
self.by_id("//*[@class='nui-ipt-input' and @maxlength='256']").send_keys("我输入了主题且添加了附件")
#添加上传附件
self.by_id("//*[@class='O0']").send_keys("E:\\test_email.txt")
sleep(5)
#点击发送按钮
self.by_id("//*[@class='jp0']/div[1]/span[2]").click()
sleep(5)
#获取发送成功后的文本信息
text =self.by_id("//*[@class='sQ1']/h1").text
self.assertIn("发送成功",text) def test_clogin(self):
'''退出登录'''
logout_text = "您已成功退出网易邮箱。"
self.obj_metcho().logout()
sleep(10)
self.result = self.by_id("html/body/section/h1").text
self.assertEqual(logout_text,self.result) def by_id(self,the_id): return self.driver.find_element_by_xpath(the_id) def tearDownClass(cls):
'''关闭浏览器'''
cls.driver.quit()

 test_bserach.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian
import unittest
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
from login import Login_Case class Serach_email(unittest.TestCase): driver = webdriver.Chrome()
@classmethod
def setUpClass(cls):
cls.driver.maximize_window()
base_url ="http://mail.126.com/"
cls.driver.get(base_url)
sleep(10) def obj_metcho(self):
'''实例化Login_Case类'''
obj=Login_Case(Serach_email.driver)
return obj #登录126.com邮箱
def test_alogin_succer(self):
user_name = "test_tx"
password = "123456tian"
login_obj = self.obj_metcho()
driver = login_obj.login_curres(user_name,password)
driver.switch_to_default_content()
sleep(10)
self.result = self.by_id("//*[@id='spnUid']").text
self.assertTrue(user_name in self.result) def test_bserach_content(self):
'''输入关键值点击搜索'''
sleep(5)
self.by_id("//*[@class='nui-ipt-input' and @type='text']").clear()
self.by_id("//*[@class='nui-ipt-input' and @type='text']").send_keys("重置成功")
self.by_id("//*[@class='nui-ipt-input' and @type='text']").send_keys(Keys.ENTER)
sleep(10)
self.result =self.by_id("//*[@class='tb0']/div/span").text
print("self_result是多少啊",self.result)
self.assertIn("重置成功",self.result) def test_cnot_serach(self):
'''输入关键字不存在'''
sleep(5)
self.by_id("//*[@class='nui-ipt-input' and @type='text']").clear()
self.by_id("//*[@class='nui-ipt-input' and @type='text']").send_keys("在哪了啊")
self.by_id("//*[@class='nui-ipt-input' and @type='text']").send_keys(Keys.ENTER)
sleep(10)
self.result = self.by_id("//*[@class='rm1']").text
self.assertIn("抱歉,没有搜索到",self.result) def test_dlogout(self):
'''退出登录'''
logout_text = "您已成功退出网易邮箱。"
self.obj_metcho().logout()
sleep(10)
self.result = self.by_id("html/body/section/h1").text
self.assertEqual(logout_text,self.result) def by_id(self,the_id):
return self.driver.find_element_by_xpath(the_id) @classmethod
def tearDownClass(cls):
cls.driver.quit()

 test_cdel.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian import unittest
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from time import sleep
from login import Login_Case class DeletEmail(unittest.TestCase):
''' 删除邮件'''
driver = webdriver.Chrome()
@classmethod
def setUpClass(cls):
driver = cls.driver
driver.maximize_window()
base_url = "http://mail.126.com/"
driver.get(base_url)
sleep(10) def obj_methond(self):
obj = Login_Case(DeletEmail.driver)
return obj #登录126邮箱
def test_alogin(self):
username = "test_tx"
password = "123456tian"
obj_driver = self.obj_methond()
driver = obj_driver.login_curres(username,password)
driver.switch_to_default_content()
sleep(10)
self.result = self.by_id("//*[@id='spnUid']").text
self.assertTrue(username in self.result) @StopIteration
def test_bdelete_email(self):
'''删除邮件'''
sleep(5)
self.driver.find_element_by_class_name("nui-tree-item-text").click()
sleep(3)
self.driver.find_elements_by_xpath("//span[@class='nui-chk-symbol']/b").pop(1).click()
sleep(5)
try:
spans = self.driver.find_elements_by_tag_name('span')
for i in spans:
if i.text =="删 除":
i.click() except Exception as e:
print("找不到删除按钮")
sleep(3)
#断言是否已删除
text = self.driver.find_element_by_css_selector("span.nui-tips-text>a").text
self.assertEqual(text,'已删除') def test_logout(self):
'''退出登录'''
logout_text = "您已成功退出网易邮箱。"
self.obj_methond().logout()
sleep(10)
self.result = self.by_id("html/body/section/h1").text
self.assertEqual(logout_text,self.result) def by_id(self,the_id):
return self.driver.find_element_by_xpath(the_id) @classmethod
def tearDownClass(cls):
cls.driver.quit()

2、Wordpress 登录 成功 和 登录失败

 test_login_case.py

from selenium import webdriver
from time import sleep
import unittest class TestCase(unittest.TestCase):
driver = webdriver.Chrome() @classmethod
def setUpClass(cls):
driver = cls.driver
base_url = "http://localhost/wordpress/wp-login.php"
driver.get(base_url)
sleep(5) def test_eoagin_success(self):
'''登录成功'''
#Arrang 准备测试数据
user_name = "admin"
password = "123456"
loging_succeed_url = "wp-admin"
sleep(5)
#Action 执行测试步骤
self.by_xpath("//input[@id='user_login']").clear()
self.by_xpath("//input[@id='user_login']").send_keys(user_name)
self.by_xpath("//input[@id='user_pass']").clear()
self.by_xpath("//input[@id='user_pass']").send_keys(password)
self.by_xpath("//input[@id='wp-submit']").click()
sleep(5)
#Assert 断言
self.assertTrue(loging_succeed_url in self.driver.current_url) #登录成功后页面发生跳转后,断言url中是否wp-admin
print("断言1 登录成功跳转url:{0}".format(self.driver.current_url))
#Assert 断言2 登录成功后断言右上角是否存在admin
greek_link=self.by_css("#wp-admin-bar-my-account >.ab-item").text
print("断言2 greek_link:{0}".format(greek_link))
self.assertTrue(user_name in greek_link) def test_ausername_passwor_all_null(self):
'''用户名和密码为空'''
#Action
self.by_css("#user_login").send_keys()
self.by_css("#user_pass").send_keys()
self.by_css("#wp-submit").click()
#Assert 断言
self.assertTrue("wordpress/wp-login.php" in self.driver.current_url) def test_buser_password_null(self):
'''输入正确用户名,密码为空'''
#Arrang 准备测试数据
username ="admin"
login_error ="错误:密码一栏为空。"
#Action 执行测试步骤
self.by_css("#user_login").send_keys(username)
self.by_css("#user_pass").send_keys()
self.by_css("#wp-submit").click() #Assert 断言
mesage_error = self.by_css("#login_error").text
self.assertTrue(login_error in mesage_error) def test_cuser_password_error(self):
'''正确的用户名,错误的密码'''
#Arrang 准备测试数据
sleep(3)
username = "admin"
password ="adafdanfn"
login_error = "错误:admin 的密码不正确。"
#Action 执行测试步骤
self.by_css("#user_login").clear()
self.by_css("#user_login").send_keys(username)
self.by_css("#user_pass").send_keys(password)
self.by_css("#wp-submit").click()
#Assert 断言
mesage_error = self.by_css("#login_error").text
self.assertTrue(login_error in mesage_error) def test_duserpassword_error(self):
'''用户名错误,密码错误'''
#Arrang 准备测试数据
sleep(3)
username = "amdinjj"
password = "112344"
login_error ="错误:无效用户名。"
#Action 执行测试步骤
self.by_css("#user_login").clear()
self.by_css("#user_login").send_keys(username)
self.by_css("#user_pass").send_keys(password)
self.by_css("#wp-submit").click()
#Assert 断言
message_error = self.by_css("#login_error").text
self.assertTrue(login_error in message_error) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) @classmethod
def tearDownClass(cls):
cls.driver.quit() if __name__ == '__main__': unittest.main()

 3、创建文章

from selenium import webdriver
from time import sleep
import unittest,time
from selenium.webdriver.common.action_chains import ActionChains class Login_Case(unittest.TestCase):
driver = webdriver.Chrome()
user_name ='admin'
password ="123456"
@classmethod
def setUpClass(cls):
driver=cls.driver
base_url = "http://localhost/wordpress/wp-login.php"
driver.get(base_url) def test_alogin(self):
'''登录成功''' self.login(self.user_name,self.password) self.assertTrue("wp-admin" in self.driver.current_url)
greeting_link = self.by_css("#wp-admin-bar-my-account > .ab-item")
self.assertTrue(self.user_name in greeting_link.text) def test_create_post(self):
self.login_as_admin() self.driver.get("http://localhost/wordpress/wp-admin/post-new.php")
sleep(5)
title ='This is my post for py se 10 %s' %(time.time())
self.by_css("#title").send_keys(title)
self.set_content('post body') #参数为正文内容post body
self.by_css("#publish").click() self.driver.get("http://localhost/wordpress/wp-admin/edit.php")
sleep(10)
new_post_tite = self.by_css('.row-title').text
self.assertTrue(new_post_tite == title) def set_content(self,text):
'''固定格式'''
js = 'document.getElementById("content_ifr").contentWindow.document.body.innerHTML="%s"' %(text)
print("js是:{0}".format(js))
self.driver.execute_script(js) def login_as_admin(self): self.login(self.user_name,self.password) def login(self,user,passwd):
'''登录方法'''
sleep(5)
self.by_css("#user_login").send_keys(user)
self.by_css("#user_pass").send_keys(passwd)
self.by_css("#wp-submit").click() def test_blogout(self):
'''退出'''
sleep(5)
above=self.by_xpath("//*[@id='wp-admin-bar-my-account']/a")
#对定位的元素执行悬停操作
ActionChains(self.driver).move_to_element(above).perform()
sleep(5)
self.by_xpath(".//*[@id='wp-admin-bar-logout']/a").click()
sleep(5) def by_xpath(self,th_xpath):
return self.driver.find_element_by_xpath(th_xpath) def by_css(self,th_css):
return self.driver.find_element_by_css_selector(th_css) @classmethod
def tearDownClass(cls):
cls.driver.quit() if __name__ == '__main__':
unittest.main()

 4、将qq.com首页上的今日话题的内容自动发表到自己的blog

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains class QQDailyHot: def __init__(self):
self.driver = webdriver.Chrome()
self.title,self.content = self.get_title_and_content_from_daily_hot()
self.username = 'admin'
self.password = "123456" def get_daily_hot_url(self):
return self.by_css("#todaytop >a").get_attribute('href') def get_title_and_content_from_daily_hot(self):
self.driver.get("http://www.qq.com/")
url = self.get_daily_hot_url()
sleep(5)
self.driver.get(url)
sleep(10)
title = self.by_xpath("//h2[@id='sharetitle']").text
print("title是:{0}".format(title)) #innerHTML获取标签之间的HTML
content = self.by_xpath(".//*[@id='articleContent']").get_attribute('innerHTML') #获取id=articleContent直接所有的标签;
print("content:{0}".format(content))
return title,content def quit(self):
'''退出'''
self.driver.quit() def create_post_from_daily_hot(self):
self.driver.get("http://localhost/wordpress/wp-login.php")
self.login_as_admin() self.driver.get("http://localhost/wordpress/wp-admin/post-new.php")
sleep(5)
self.by_css("#title").send_keys(self.title)
self.set_content(self.content)
sleep(10)
self.by_xpath("//*[@id='publish']").click() def set_content(self,text):
text = text.strip()
js = 'document.getElementById("content_ifr").contentWindow.document.body.innerHTML=\'%s\'' %(text)
print(js)
self.driver.execute_script(js)
def login_as_admin(self):
'''登录'''
sleep(5)
self.by_xpath("//*[@id='user_login']").send_keys(self.username)
self.by_xpath(".//*[@id='user_pass']").send_keys(self.password)
self.by_xpath("//*[@id='wp-submit']").click() def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) if __name__ == '__main__':
datly_hot = QQDailyHot()
datly_hot.create_post_from_daily_hot()
datly_hot.quit()

 5、实现创建post的数据驱动

json_data.py   数据文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian import json
class Json_Data:
def data(self): data = [
{
'title': "Don't cry because it's over, smile because it happened",
'content': "Don"
}, {
'title': "Be yourself; everyone else is already taken",
'content': "Be"
}, {
'title': 'So many books, so little time',
'content': 'So'
} ] return json.dumps(data)

 test_json_data.py 实现代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian import json
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
from json_data import Json_Data
class Reat_dict:
def __init__(self):
self.driver = webdriver.Chrome()
self.base_url = "http://localhost/wordpress/wp-login.php" self.user = "admin"
self.password ="123456"
self.obj_data = Json_Data()
self.data = self.data_dict() def data_dict(self):
resutl_data = self.obj_data.data()
return json.loads(resutl_data) def login(self):
'''登录'''
sleep(10)
self.by_xpath("//*[@id='user_login']").send_keys(self.user)
self.by_xpath("//*[@id='user_pass']").send_keys(self.password)
self.by_xpath("//*[@id='wp-submit']").click() def test_creatnew_Wordpress(self):
self.driver.get(self.base_url)
self.login()
sleep(5)
for line in self.data:
self.driver.get("http://localhost/wordpress/wp-admin/post-new.php")
title = line['title']
sleep(5)
self.by_xpath("//*[@id='title']").send_keys(title)
content_1 = line['content']
sleep(5)
self.set_content(content_1)
sleep(5)
self.by_css("#publish").click() def set_content(self,text):
text = text.strip()
js = 'document.getElementById("content_ifr").contentWindow.document.body.innerHTML=\'%s\'' %(text)
self.driver.execute_script(js) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def logout(self):
'''退出登录'''
above = self.by_xpath("//*[@id='wp-admin-bar-my-account']/a")
ActionChains(self.driver).move_to_element(above).perform()
sleep(5)
self.by_xpath("//*[@id='wp-admin-bar-logout']/a").click() def quit(self):
self.driver.quit() if __name__ == '__main__':
obj = Reat_dict()
obj.test_creatnew_Wordpress()
obj.login()
obj.logout()
obj.quit()

 6、粉丝反馈表单自动化脚本:

需求:

  • 服务质量5颗星
  • 喜欢的内容选择各种公开课
  • 对交流群的意见需要填写
  • 留下自己正确的联系方式
  • 点击提交
  • 不需要断言,能提交成功就可以
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains class Fans_Table:
def __init__(self): self.driver = webdriver.Chrome()
self.driver.maximize_window()
base_url = "https://jinshuju.net/f/kRXoEv"
self.driver.get(base_url)
sleep(5)
self.test_fans_home() def test_fans_home(self):
result=self.by_sxpaths(".//*[@class='selectable type-star']/i")
for i in result:
if not i.is_selected():
i.click()
sleep(5)
self.by_scss(".choices.font-family-inherit>label").pop(1).click() self.by_css("#entry_field_3").send_keys("我希望可以学到更多的知识")
sleep(5)
self.by_css("#entry_field_4").send_keys("135623@qq.com")
js ="window.scrollTo(1903,1166)" #提交按钮在底部,需要设置分辨率
self.driver.execute_script(js) #竖滚单条
sleep(5)
self.by_xpath("//*[@id='new_entry']/div[3]/div/div[2]/input[1]").click() def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) def by_sxpaths(self,the_xps):
return self.driver.find_elements_by_xpath(the_xps) def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def by_scss(self,the_scss):
return self.driver.find_elements_by_css_selector(the_scss) if __name__ == '__main__':
obj = Fans_Table()

7、百度天气

test_baidu_weather.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from selenium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait class WeatherNotification:
def __init__(self,city):
self.driver = webdriver.Chrome()
self.goto_weather_page(city) def goto_weather_page(self,cityname):
keyword = cityname + '天气'
self.driver.get("https://www.baidu.com/")
self.by_css("#kw").send_keys(keyword)
wait = WebDriverWait(self.driver,5) #隐式等待,参数5为设置等待时间,默认每隔0.5秒检测元素是否存在
wait.until(lambda dr: dr.find_element_by_class_name('op_weather4_twoicon_container_div').is_displayed()) @property
def tomorrow_block(self):
result=self.driver.find_element_by_class_name('op_weather4_twoicon_day') return result def quit(self):
self.driver.quit() def send_email(self,email,content):
print('Send email"%s'%(content)) def get_temperature(self):
tmp_txt = self.by_css(".op_weather4_twoicon_temp").text
print("tmp_txt等于",tmp_txt)
high_temp = tmp_txt.replace("℃",'').split('~')[-1].strip()
print("hight_tmep",high_temp)
return int(high_temp) def get_weather(self):
wt_txt = self.tomorrow_block.find_element_by_class_name("op_weather4_twoicon_weath").text
print("wt_txt等于",wt_txt)
if '雨' in wt_txt:
return 'raining'
else:
return 'not raining' def send_notification(self,email):
weather = self.get_weather()
print("weather等于",weather)
temmperature = self.get_temperature() print("temmperature等于:",temmperature)
content = ''
if weather == 'raining':
content += '明天下雨'
else:
content += '明天晴天' print("content是什么啊",content) if temmperature < 10:
content +="温度低于10度,请注意保暖" if temmperature >30:
content +="温度高于30度,请注意高温" self.quit()
print("最后的content是什么",content) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) if __name__ == '__main__':
obj = WeatherNotification("深圳")
obj.send_notification('xxooxxww@qq.com')

 8、wordpress删除文章

test_deleter.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
import time
import unittest class TestCase(unittest.TestCase): driver = webdriver.Chrome()
@classmethod
def setUpClass(cls):
base_url ="http://localhost/wordpress/wp-login.php"
cls.driver.get(base_url)
cls.driver.maximize_window()
cls.driver.implicitly_wait(5) def login(self):
'''登录'''
user_name ='admin'
passwrod ='123456'
self.by_css("#user_login").send_keys(user_name)
self.by_css("#user_pass").send_keys(passwrod)
self.by_css("#wp-submit").click() def test_aCeate_post(self):
'''创建帖子'''
self.login()
title = "我是来测试帖子的:{0}".format(time.time())
content = "post data"
self.creat_post(title,content)
sleep(3)
self.goto_posts_list_page()
new_post_title = self.by_css(".row-title").text
self.assertTrue(new_post_title == title) def test_bdelete_post(self):
'''删除帖子'''
title = "测试发帖发完后我又删除了:{0}".format(time.time())
content = "post data delete"
post_id = self.creat_post_and_return_its_id(title,content)
self.goto_posts_list_page()
row_id = "post-{0}".format(post_id)
new_post_row = self.by_id(row_id)
ActionChains(self.driver).move_to_element(new_post_row).perform()
new_post_row.find_element_by_css_selector("a.submitdelete").click()
sleep(3)
self.logout() def creat_post_and_return_its_id(self,title,content):
self.creat_post(title,content)
return self.by_id("sample-permalink").text.split("=")[-1] #返回发帖的id def creat_post(self,title,content):
'''输入帖子title和内容,点击创建'''
self.driver.get("http://localhost/wordpress/wp-admin/post-new.php")
self.by_css("#title").send_keys(title)
self.set_content(content)
sleep(3)
self.by_css("#publish").click() def set_content(self,text):
js = 'document.getElementById("content_ifr").contentWindow.document.body.innerHTML="%s"' %(text)
self.driver.execute_script(js) def goto_posts_list_page(self):
self.driver.get("http://localhost/wordpress/wp-admin/edit.php")
sleep(3)
def logout(self):
'''退出登录'''
move_element = self.by_xpath("//*[@id='wp-admin-bar-my-account']/a")
ActionChains(self.driver).move_to_element(move_element).perform()
sleep(5)
self.by_xpath(".//*[@id='wp-admin-bar-logout']/a").click()
text ="您已登出。"
result =self.by_css(".message").text.strip()
self.assertTrue(text==result) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def by_id(self,the_id):
return self.driver.find_element_by_id(the_id) @classmethod
def tearDownClass(cls):
cls.driver.quit() if __name__ == '__main__': unittest.main()
 

 9、知乎(完成一半代码)

zhiu.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian
from selenium import webdriver
from datetime import date class ZhiHu:
def __init__(self):
self.daily_url = 'https://www.zhihu.com/explore#daily-hot'
self.monthly_url = 'https://www.zhihu.com/explore#monthly-hot'
self.dr = webdriver.Chrome() def get_daily_hots_urls(self):
self.dr.get(self.daily_url)
self.dr.maximize_window()
self.dr.implicitly_wait(5)
wrap_div = self.by_css(".tab-panel")
title_url_elements = wrap_div.find_elements_by_css_selector(".question_link")
assert len(title_url_elements) == 5
urls =[]
for title in title_url_elements:
urls.append(title.get_attribute('href'))
return urls def get_daily_hots(self):
result = []
hots_urls = self.get_daily_hots_urls()
for url in hots_urls:
result.append(self.get_answer(url))
return result def get_answer(self,url):
self.dr.get(url)
article = {}
article['question'] = self.by_xpath(".//*[@id='root']/div/main/div/div[1]/div[2]/div[1]/div[1]/h1").text #提问的问题
article['author'] = self.by_xpath(".//*[@id='root']/div/main/div/div[2]/div[1]/div[2]/div/div/div[1]/div/div[1]/div/div[1]").text #作者
article['answer'] = self.by_css(".RichContent-inner").get_attribute('innerHTML') #回答的正文
return article def by_css(self,the_css):
return self.dr.find_element_by_css_selector(the_css) def by_xpath(self,the_xpath):
return self.dr.find_element_by_xpath(the_xpath) def by_elements_css(self,thes_css):
return self.dr.find_elements_by_css_selector(thes_css) class ZhihuReporter: def __init__(self,path):
self.report_path = path
self.open_file = open(path,'w+',encoding="utf-8")
def write_body(self):
self.open_file.write('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
<title>Title</title>
</head>
<body>
<h3>知乎{0}最热</h3>
'''.format(date.today().strftime("%Y_%m_%d")))
def write_article(self,articles):
# self.open_file.write('知乎%s最热</h3>' %(date.today().strftime("%Y_%m_%d")))
for article in articles:
# article_html = '<h3>%s<small>%s</small></h3>' %(article['question'], article['author'])
# article_html += article['answer']
self.open_file.write('''
<div class="container>
<h3>{0}<small>{1}</small></h3>
{2}
</div><hr>
'''.format(article['question'],article['author'],article['answer']))
# self.open_file.write(article)
self.open_file.write('''
</body>
</html> ''') def build_articel_report(self,articles):
self.write_body()
self.write_article(articles)
self.open_file.close() if __name__ == '__main__': obj = ZhiHu()
articles = obj.get_daily_hots()
report_name ='zhihu_{0}.html'.format(date.today().strftime('%Y_%m_%d'))
reporter = ZhihuReporter(report_name) reporter.build_articel_report(articles)

 10、登录http://www.smzdm.com/,点击签到积分按钮,获取每日积分

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep class TestCase:
def __init__(self,username,password):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(5)
self.base_url = "http://www.smzdm.com/"
self.driver.get(self.base_url)
self.username = username
self.password = password def loging(self):
self.by_css("#skip-step").click()
self.by_css(".nav-logins .J_login_trigger").click()
sleep(2)
login_div=self.by_css("#J_login_popup")
assert login_div.is_displayed(),'登录框未显示' login_frame = self.by_css("#J_login_iframe")
self.driver.switch_to_frame(login_frame) self.by_css("#username").click()
self.by_css("#username").send_keys(self.username)
self.by_css("#password").click()
self.by_css("#password").send_keys(self.password)
sleep(2)
self.by_css("#login_submit").click()
self.driver.switch_to_default_content() def get_integral(self):
sleep(5)
try:
score_btn = self.by_css(".J_punch")
assert score_btn.is_displayed(),'积分按钮未显示'
self.by_css(".J_punch").click()
sleep(3)
assert score_btn.get_attribute("class")=="J_punch"
print("点击积分按钮",score_btn.text)
except NoSuchElementException:
score_btn = self.by_css(".J_punch").text
print("未找到积分按钮:{0}".format(score_btn)) def logout(self):
'''退出登录'''
sleep(5)
obj_mover=self.by_css(".nav-username.J_nav_username")
ActionChains(self.driver).move_to_element(obj_mover).perform()
self.by_xpath(".//*[@id='global-nav']/div/div/ul/li[3]/ul/li[12]/a").click()
sleep(2)
home_test=self.by_css(".nav-logins").text
print("退出登录到首页:{0}".format(home_test))
self.driver.quit() def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) if __name__ == '__main__':
username = "135******620"
password = "**********"
obj = TestCase(username,password)
obj.loging()
obj.logout()

 11、试吃报名:https://jinshuju.net/f/kl2yl3

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:tian from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import sleep
from selenium.webdriver.support.ui import Select #下拉菜单进行定位 class TestCase:
def __init__(self): self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(5)
self.base_url = "https://jinshuju.net/f/kl2yl3"
self.driver.get(self.base_url)
self.list_table = {"weixing":"352932341","name":"张帅","phone":13580453523,"email":"xxoosss@qq.com","age":12} def post_table(self):
self.by_css("#entry_field_1").click()
self.by_css("#entry_field_1").send_keys(self.list_table['weixing']) self.by_css("#entry_field_2").click()
self.by_css("#entry_field_2").send_keys(self.list_table['name']) self.by_css("#entry_field_3").click()
self.by_css("#entry_field_3").send_keys(self.list_table['phone']) self.by_css("#entry_field_4").click()
self.by_css("#entry_field_4").send_keys(self.list_table['email']) self.by_css("#entry_field_5").click()
self.by_css("#entry_field_5").send_keys(self.list_table['age']) Select(self.by_css("#entry_field_6_province")).select_by_value("广东省")
sleep(2)
Select(self.by_css("#entry_field_6_city")).select_by_value("深圳市")
sleep(2)
Select(self.by_css("#entry_field_6_district")).select_by_value("福田区")
sleep(2)
self.by_css("#entry_field_6_street").send_keys("大石镇130号")
sleep(2)
self.by_xpath(".//*[@id='new_entry']/div[3]/div/div[1]/div[7]/div/div[2]/div/label[2]").click()
sleep(2) # self.by_xpath(".//*[@id='new_entry']/div[3]/div/div[1]/div[8]/div/div[2]/div/label[1]/div[1]/i").click()
obj_select=self.driver.find_elements_by_css_selector(".choice-description") for line in obj_select:
if line.text.strip() =="周期长":
line.click()
else:
pass
sleep(2) self.by_css("#entry_field_9").click()
self.by_css("#entry_field_9").send_keys("互联网上") def by_css(self,the_css):
return self.driver.find_element_by_css_selector(the_css) def by_xpath(self,the_xpath):
return self.driver.find_element_by_xpath(the_xpath) if __name__ == '__main__': obj = TestCase()
obj.post_table()

Python—UI自动化完整实战的更多相关文章

  1. (appium+python)UI自动化_09_unittest批量运行测试用例&amp;生成测试报告

    前言 上篇文章[(appium+python)UI自动化_08_unittest编写测试用例]讲到如何使用unittets编写测试用例,并执行测试文件.接下来讲解下unittest如何批量执行测试文件 ...

  2. (appium+python)UI自动化_07_app UI自动化实例【叮咚搜索加车为例】

    前言 初学UI自动化的小伙伴,在配置好appium+python自动化环境后,往往不知道如何下手实现自动化.小编在初期学习的时候也有这种疑惑,在此以叮咚买菜app-搜索加车为实例,展示下appium是 ...

  3. (appium+python)UI自动化_01_自动化环境搭建【MAC版】

    Appium简介 Appium是一个开源的.跨平台的测试框架,主要用来进行app UI自动化,适用于原生应用.混合应用和移动网页应用(H5页面).目前支持Python.JavaScript.Objec ...

  4. python UI自动化之切换iframe

    python+selenium写UI自动化的时候,经常会遇到需要切换iframe的情况,这里介绍几种切换iframe的方式 1.使用id定位 driver.switch_to.frame(" ...

  5. (appium+python)UI自动化_03_元素定位工具

    前言 在UI自动化过程中,需要对手机app上的元素进行定位,然后进一步编写自动化脚本操作app.定位元素首先需要定位工具来辅助查看页面元素.小编常用的定位工具有2种,分别是uiautomatorvie ...

  6. python ui自动化之元素定位和常用操作

    做ui自动化的最基础的就是页面元素定位了,如果连页面元素都定位不到,自动化从何谈起呢?接下来我们就看看页面元素定位的方法吧!(这里就用百度页面来进行演示) 一.最通用的几种定位方式: 1.通过id定位 ...

  7. python UI自动化实战记录三:pageobject-基类

    脚本思路: 使用pageobject模式,写一个basepage基类,所有页面的通用方法封装到基类中.比如打开页面,关闭页面,等待时间,鼠标移到元素上,获取单个元素,获取一组元素,获取元素的子元素,截 ...

  8. python UI自动化实战记录二:请求接口数据并提取数据

    该部分记录如何获取预期结果-接口响应数据,分成两步: 1 获取数据源接口数据 2 提取后续页面对比中要用到的数据 并且为了便于后续调用,将接口相关的都封装到ProjectApi类中. 新建python ...

  9. python UI自动化实战记录十一: 总结

    首先说说为什么想起来用自动化脚本来实现该项目的自动化. 工作还是以手工测试为主,业务驱动型的项目大概就是这样,业务不停地变,不断的迭代. 自动化测试实施的先决条件: 一 得有时间. 如果有时间大部分的 ...

随机推荐

  1. spring mvc 数据校验

    1.需要导入的jar包: slf4j-api-1.7.21.jar validation-api-1.0.0.GA.jar hibernate-validator-4.0.1.GA.jar 2.访问页 ...

  2. 转,SelectNodes + XPath

    XPath 是 XML 的内容,这里 SelectNodes 是 C# 中 XmlDocument 或 XmlNode 的一个方法.SelectNodes 使用 XPath 来选取节点. 重要语法 S ...

  3. cocos2dx游戏开发——捕鱼达人mini版学习笔记(一)——FishAchor的搭建

    一.创建文件· FishAchor.h还有FishAchor.cpp. 主要就是创建每种鱼的类,方便以后的取用~,很多是重复性的操作,然后我们是mini版,暂时也就加入大概6钟鱼就好= =,然后我们现 ...

  4. MySQL语句进行分组后的含有字段拼接方法

    MySQL语句: SELECT GROUP_CONCAT(DISTINCT transaction_no) FROM `lm_wh_trans` GROUP BY staff_code; 如果tran ...

  5. Mock.js 与 fiddler 前端模拟数据与拦截请求

    最近 工作需要  接触了Mock.js. Mock.js 是一款模拟数据生成器,旨在帮助前端攻城师独立于后端进行开发,帮助编写单元测试.提供了以下模拟功能: 根据数据模板生成模拟数据 模拟 Ajax ...

  6. Hadoop: LongWritable cannot be cast to org.apache.hadoop.io.IntWritable

    写MR Job的时候遇到一个坑爹的异常: LongWritable cannot be cast to org.apache.hadoop.io.IntWritable 当写Map的时候,key的默认 ...

  7. vue请求java服务端并返回数据

    最近在自学vue怎么与java进行数据交互.其实axios还是挺简单的,与ajax请求几乎一样,无外乎也就是要解决下跨域的问题. 废话不多说了,直接贴代码,一看就懂! //向springmvc Con ...

  8. BZOJ4036 [HAOI2015]按位或 FWT

    原文链接https://www.cnblogs.com/zhouzhendong/p/BZOJ4036.html 题目传送门 - BZOJ4036 题意 刚开始你有一个数字 $0$ ,每一秒钟你会随机 ...

  9. iperf/iperf3网络测试工具的安装与使用

    1.官网及下载路径: iperf3 homepage at: http://software.es.net/iperf/Report bugs to: https://github.com/esnet ...

  10. char函数绕过魔术引号注入

    我目前学习到的绕过魔术引号的几种方法(如果知道还有别的请万望告之): 1.倘若服务端是GBK可以尝试宽字节注入 2.使用char函数绕过魔术引号进行注入 3.同char函数类似的函数,例如bin(转换 ...