Python憑借簡潔語法和豐富庫生態(tài),成為自動化測試、爬蟲、運(yùn)維的主流工具。在Web自動化中,Selenium可模擬用戶操作瀏覽器,完成表單填寫、數(shù)據(jù)抓取等任務(wù)。通過unittest或pytest框架實現(xiàn)測試用例管理,結(jié)合Allure生成可視化報告。在接口測試中,Requests庫能快速發(fā)送HTTP請求,斷言響應(yīng)狀態(tài)碼和數(shù)據(jù),適合API自動化。
python自動化selenium框架
一、框架核心組件設(shè)計
基礎(chǔ)配置層
配置文件:使用config.ini或.env管理瀏覽器類型、URL、超時時間等參數(shù),示例:
ini[DEFAULT]BROWSER = chromeIMPLICIT_WAIT = 10BASE_URL = https://example.com
日志模塊:通過logging庫記錄執(zhí)行過程,支持控制臺和文件輸出:
pythonimport logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler('test.log'), logging.StreamHandler()])
瀏覽器驅(qū)動管理
動態(tài)加載驅(qū)動:使用webdriver-manager自動下載對應(yīng)版本的驅(qū)動:
pythonfrom selenium.webdriver.chrome.service import Servicefrom webdriver_manager.chrome import ChromeDriverManagerdriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
多瀏覽器支持:通過工廠模式動態(tài)選擇瀏覽器:
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))
頁面類繼承:具體頁面繼承基類并實現(xiàn)專屬方法:
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)

二、高級功能實現(xiàn)
數(shù)據(jù)驅(qū)動測試
參數(shù)化測試:使用pytest的@pytest.mark.parametrize讀取CSV/Excel數(shù)據(jù):
pythonimport pytestimport pandas as [email protected]("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
行為驅(qū)動開發(fā)(BDD)
Gherkin語法:通過behave庫編寫自然語言測試用例:
gherkinFeature: LoginScenario: Successful loginGiven I am on the login pageWhen I enter valid credentialsThen I should see the dashboard
步驟定義:關(guān)聯(lián)Python代碼與Gherkin步驟:
pythonfrom behave import *@given('I am on the login page')def step_impl(context):context.driver.get("https://example.com/login")
報告與監(jiān)控
Allure報告:生成可視化測試報告:
pythonimport pytestpytest.main(["--alluredir=./reports"])# 生成報告命令:allure serve ./reports
失敗重試機(jī)制:使用pytest-rerunfailures插件自動重試失敗用例:
pythonpytest.main(["--reruns=2"])
三、框架優(yōu)化建議
隱式/顯式等待優(yōu)化
優(yōu)先使用顯式等待(WebDriverWait)替代time.sleep(),提升執(zhí)行效率。
無頭模式與Docker集成
在CI/CD中啟用無頭模式:
pythonoptions = webdriver.ChromeOptions()options.add_argument("--headless")driver = webdriver.Chrome(options=options)
通過Docker鏡像部署測試環(huán)境:
bashdocker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome
跨瀏覽器兼容性測試
使用Selenium Grid實現(xiàn)分布式測試:
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)
四、完整項目結(jié)構(gòu)示例
selenium_framework/├── config/│ ├── config.ini # 基礎(chǔ)配置│ └── __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 # 數(shù)據(jù)驅(qū)動工具├── reports/ # 測試報告└── requirements.txt # 依賴列表
通過以上設(shè)計,框架可實現(xiàn)高復(fù)用性、易維護(hù)性,并支持從本地開發(fā)到CI/CD的全流程自動化測試。構(gòu)建自動化框架需分層設(shè)計,基礎(chǔ)層封裝瀏覽器驅(qū)動、日志記錄、配置管理。頁面層采用POM模式,分離頁面元素與操作邏輯。