1.首先下载python:https://www.python.org/getit/    #将python添加到环境变量,按下CTRL+R键输入CMD回车,执行命令python,能执行就说明环境变量已添加

2.其次下载selenium框架,用python的pip下载:打开CMD,输入pip.exe install selenium。

#下载selenium3需要下载浏览器驱动程序

3.不同的浏览器需要下载不同的浏览器驱动,驱动版本需对应浏览器版本

下载geckodriver:https://github.com/mozilla/geckodriver/releases/    #火狐专用,将下载的文件添加到环境变量,也可以放在Python36\Scripts目录下就行(Python36\Scripts目录在环境变量)。

4.cmd中,输入Python,然后输入from selenium import webdriver ,再输入webdriver.Firefox(),如果可以启动火狐浏览器,说明安装OK

5.selenium中几个常用的控件定位方式,id、class、text、xpath。位了定位准确,要唯一定位,就是你定位的元素是唯一的,id是唯一的值,class是控件常用的属性值,link_text是文本超链接,xpath是相对定位

6:可选择BeautifulReport测试框架用来生成测试报告,用python的pip下载:打开CMD,输入pip install BeautifulReport

例子:

以下的main方法

import geckodriver
from BeautifulReport import BeautifulReport
import unittest

if __name__ == '__main__':
    suite = unittest.TestSuite()#创建用例套件
    suite.addTest(geckodriver.Baidu('test_baidu'))#添加用例到测试套件
    # 测试报告:BeautifulReport
    #实例化测试报告框架,且将测试用例添加到测试报告中
    reports = BeautifulReport(suites=suite)
    #定义测试报告注释,其他均为默认值
    reports.report(description='测试报告')

以下是测试用例

import time
from selenium import webdriver
import unittest
#继承unittest框架中的TestCase类方法,表示为测试用例
class Baidu(unittest.TestCase):
    def test_baidu(self) -> None:
        '''百度搜索按钮'''#用例描述
        #如若报错找不到驱动程序,则将驱动程序路径写进去
        self.driver = webdriver.Firefox(executable_path=r'C:\Program Files\Mozilla Firefox\geckodriver.exe')
        #访问URL
        self.driver.get("http://www.baidu.com")
        #执行动作:输入框输入’有道‘
        self.driver.find_element_by_id("kw").send_keys("有道")
        #执行动作:点击百度按钮
        self.driver.find_element_by_id("su").click()
        #执行动作:清除输入框
        self.driver.find_element_by_id("kw").clear()
        #休息两秒
        time.sleep(2)
        #断言,打开的页面中的title为“有道_百度搜索”
        self.assertEqual('有道_百度搜索', self.driver.title)
        print(self.driver.title)
        #关闭浏览器
        self.driver.quit()

更多推荐