前几章我们已经准备好了自动化脚本的前期步骤,接下来可以编写自动化框架了,首先创建基础动作文件夹,比如scrip,在这里面编写基础操作,这边的话是写的是百度的脚本,因此取名为baidu_test。
然后在baidu_test.py上面写入我们的基础操作比如打开、搜索、等操作,源码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from selenium import webdriver
class BaiDu:
def __init__(self):
self.driver = webdriver.Chrome(r"D:\driver\chromedriver.exe")
# 初始化浏览器驱动,会自动打开浏览器
def get_web(self):
self.driver.get("http://www.baidu.com")
# 打开百度网页
def input(self, text):
self.driver.find_element_by_xpath("//*[@id='kw']").send_keys(text)
# 在搜索框里输入text文本
def search(self):
self.driver.find_element_by_xpath("//*[@id='su']").click()
# 点击搜索按钮
写好基础操作后,我们回到test开头文件夹下的test_pytest.py文件上,写入测试用例,源码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from scrips.driver.baidu_test import BaiDu
import time
class TestPy:
def setup_class(self):
self.baidu = BaiDu()
def test_get_url(self):
self.baidu.get_web()
def test_input_text(self):
self.baidu.get_web()
time.sleep(5)
self.baidu.input("今日新闻")
def test_search(self):
self.baidu.get_web()
time.sleep(5)
self.baidu.input("今日新闻")
time.sleep(3)
self.baidu.search()
最后回到外面的启动函数Main.py上运行,运行结果如下:
最终输出报告html为: