Web自动化测试,基于python+selenium+pytest
一、环境准备
1.1 驱动安装
本文使用的插件及操作文件:提取密码:02q3 百度云
1.1.1 chrome驱动
下载地址:点击这里
Windows 系统下注意chrome浏览器版本与chromedriver版本的对应即可, 将chromedriver.exe 复制到 项目根目录,调用驱动时加入驱动的绝对路径,如下所示:
driver=webdriver.Chrome(os . path . abspath(“chromedriver . exe”))
1.1.2 firefox驱动
下载地址:点击这里,启动firefox。
driver=webdriver.Firefox(os.path.abspath("geckodriver.exe"))
1.1.3 IE驱动
下载地址:点击这里, 启动IE。
driver = webdriver.Ie(os . path . abspath('IEDriverServer . exe'))
当调用quit方法关闭浏览器时,需要去掉IE选项中的保护模式才能关闭浏览器 。
示例:
三个浏览器任选其一,这里以chrome为例:
# 创建文件 test_web.py
import os
import pytest
from time import sleep
# 连接到浏览器的绝对路径,三个任选其一
chrome_path=os.path.abspath('drivers/chromedriver.exe')
# firefox_path=os.path.abspath('drivers/geckodriver.exe')
# ie_path=os.path.abspath('drivers/IEDriverServer.exe')
# 可选择输出查看路径是否正确
# print(chrome_path)
# 创建要访问的网址:
url= 'https://www.baidu.com/'
创建装饰器对象,打开浏览器
@pytest.fixture()
def open_browser():
# 将路径添加到要被执行的浏览器
driver = webdriver.Chrome(executable_path=chrome_path,options=option)
# driver = webdriver.Firefox(executable_path=firefox_path)
# driver = webdriver.Ie(executable_path=ie_path)
driver.get(url) # 指向访问的网站
sleep(2) # 休眠2s,保持运行的稳定
yield driver # 挂起该网站
driver.quit() # 退出关闭网站
创建测试用例
def test_case_01(open_browser):
print('开始执行测试用例')
driver = open_browser
print(driver)
print('测试执行结束')
assert True
调用用例
if __name__ == '__main__':
args=['-s','-q','test_web.py']
pytest.main(args)
1.2 selenium 安装
pip install selenium
调用 selenium
from selenium import webdriver
1.3 chrome 启动参数( 以下皆以chrome浏览器作为举例对象)
–headless: 无界面运行
–start-maximized: 窗口最大化运行
–incognito: 隐身模式运行
def open_browser():
option = webdriver.ChromeOptions()
# option.add_argument('--headless') # 无界面运行
option.add_argument('--start-maximized') # 窗口最大化运行
option.add_argument('--incognito') # 隐身模式运行
–不展示“浏览器正在被自动化程序控制”提示
option.add_experimental_option('excludeSwitches', ['enable-automation'])
二、 常用对象定位方法
id
name
classname
link_text
partial_link_text
tag_name
xpath
css_selector
2.1 id 和 name
以百度首页为例,按F12进入开发者模式,点击搜索栏,定位到对应的代码如下:
<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off"><