Python凭借简洁语法和丰富库生态,成为自动化测试、爬虫、运维的主流工具。在Web自动化中,Selenium可模拟用户操作浏览器,完成表单填写、数据抓取等任务。通过unittest或pytest框架实现测试用例管理,结合Allure生成可视化报告。在接口测试中,Requests库能快速发送HTTP请求,断言响应状态码和数据,适合API自动化。
python自动化selenium框架
一、框架核心组件设计
基础配置层
配置文件:使用config.ini或.env管理浏览器类型、URL、超时时间等参数,示例:
ini[DEFAULT]BROWSER = chromeIMPLICIT_WAIT = 10BASE_URL = https://example.com
日志模块:通过logging库记录执行过程,支持控制台和文件输出:
pythonimport logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler('test.log'), logging.StreamHandler()])
浏览器驱动管理
动态加载驱动:使用webdriver-manager自动下载对应版本的驱动:
pythonfrom selenium.webdriver.chrome.service import Servicefrom webdriver_manager.chrome import ChromeDriverManagerdriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
多浏览器支持:通过工厂模式动态选择浏览器:
pythondef get_driver(browser_name):if browser_name.lower() == 'chrome':return webdriver.Chrome()elif browser_name.lower() == 'firefox':return webdriver.Firefox()raise ValueError("Unsupported browser")
页面对象模型(POM)
基类封装:在BasePage中定义通用方法:
pythonfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECclass BasePage:def __init__(self, driver):self.driver = driverdef find_element(self, *locator):return WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(locator))
页面类继承:具体页面继承基类并实现专属方法:
pythonclass LoginPage(BasePage):USERNAME_INPUT = (By.ID, "username")PASSWORD_INPUT = (By.ID, "password")def login(self, username, password):self.find_element(*self.USERNAME_INPUT).send_keys(username)self.find_element(*self.PASSWORD_INPUT).send_keys(password)
二、高级功能实现
数据驱动测试
参数化测试:使用pytest的@pytest.mark.parametrize读取CSV/Excel数据:
pythonimport pytestimport pandas as pd@pytest.mark.parametrize("username,password", pd.read_csv("test_data.csv").values)def test_login(username, password):login_page = LoginPage(driver)login_page.login(username, password)assert "Dashboard" in driver.title
行为驱动开发(BDD)
Gherkin语法:通过behave库编写自然语言测试用例:
gherkinFeature: LoginScenario: Successful loginGiven I am on the login pageWhen I enter valid credentialsThen I should see the dashboard
步骤定义:关联Python代码与Gherkin步骤:
pythonfrom behave import *@given('I am on the login page')def step_impl(context):context.driver.get("https://example.com/login")
报告与监控
Allure报告:生成可视化测试报告:
pythonimport pytestpytest.main(["--alluredir=./reports"])# 生成报告命令:allure serve ./reports
失败重试机制:使用pytest-rerunfailures插件自动重试失败用例:
pythonpytest.main(["--reruns=2"])
三、框架优化建议
隐式/显式等待优化
优先使用显式等待(WebDriverWait)替代time.sleep(),提升执行效率。
无头模式与Docker集成
在CI/CD中启用无头模式:
pythonoptions = webdriver.ChromeOptions()options.add_argument("--headless")driver = webdriver.Chrome(options=options)
通过Docker镜像部署测试环境:
bashdocker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome
跨浏览器兼容性测试
使用Selenium Grid实现分布式测试:
pythonfrom selenium import webdriverfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilitiescaps = DesiredCapabilities.FIREFOXdriver = webdriver.Remote(command_executor='http://grid-hub:4444/wd/hub', desired_capabilities=caps)
四、完整项目结构示例
selenium_framework/├── config/│ ├── config.ini # 基础配置│ └── __init__.py├── pages/│ ├── base_page.py # POM基类│ ├── login_page.py # 登录页面对象│ └── __init__.py├── tests/│ ├── conftest.py # pytest fixture│ ├── test_login.py # 测试用例│ └── __init__.py├── utils/│ ├── logger.py # 日志模块│ └── data_reader.py # 数据驱动工具├── reports/ # 测试报告└── requirements.txt # 依赖列表
通过以上设计,框架可实现高复用性、易维护性,并支持从本地开发到CI/CD的全流程自动化测试。构建自动化框架需分层设计,基础层封装浏览器驱动、日志记录、配置管理。页面层采用POM模式,分离页面元素与操作逻辑。