安裝環境並運行一個簡單例子
1. 安裝python
官網地址:https://www.python.org/downloads/
- 不要用python2.7,請毫不猶豫的選擇python3。
- 安裝時,記得勾選上"Add Python to Path" 選項。
- 安裝后,在命令窗口中,輸入"python -v", 檢查是否python3安裝成功,版本是否正確。
2. 安裝selenium
pip install selenium
如果安裝出現超時的情況,可以換上其它源。
pip install selenium-i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
安裝后, 執行'pip list'命令, 列出所有安裝了的包.
pip list
3. webdriver(chrome為例)
下載與你的chrome對應版本的chrome driver。 (下載地址: https://npm.taobao.org/mirrors/chromedriver/)
每個版本的文件夾中,帶有一個note文件,可以用來查看適用的chrome版本。
4. 運行一個簡單的例子
demo.py
#coding=utf-8
from selenium import webdriver
chrome_driver = 'C:\Users\L\AppData\Local\Google\Chrome\Application\chromedriver.exe' #chrome_driver 存放位置
driver = webdriver.Chrome(executable_path=chrome_driver)
driver.get("https://www.baidu.com/")
driver.find_element(By.ID, "kw").send_keys("demo")
driver.find_element(By.ID, "su").click()
driver.quit()
執行腳本:
python demo.py
如果沒有配置webdriver的環境變量而導致selenium找不到driver報錯。也可通過在代碼中設置webdriver的位置,來解決這個問題。
使用Selenium IDE錄制腳本
用Selenium IDE插件,即使不會selenium語句也可以快速寫好腳本。
步驟:
- 在chrome中安裝selenium IDE插件
- 錄制腳本
- 將腳本導出為python格式


- 導出后打開文件:
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class TestDemotest():
def setup_method(self, method):
self.driver = webdriver.Chrome()
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_demotest(self):
# Test name: demo_test
# Step # | name | target | value | comment
# 1 | open | / | |
self.driver.get("https://www.baidu.com/")
# 2 | type | id=kw | demo |
self.driver.find_element(By.ID, "kw").send_keys("demo")
# 3 | click | id=su | |
self.driver.find_element(By.ID, "su").click()
使用pytest並生成報告
在使用selenium IDE導出的文件中,可以看到使用了pytest包。它是 python 的第三方單元測試框架。
安裝pytest
pip install pytest -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
安裝pytest-html
pip install -U pytest-html -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
運行腳本並生成報告
pytest demo.py --html=test_report.html
進階:讀取excel,作為測試用例的數據
安裝xlrd插件
pip install xlrd -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
讀取excel
ExcelHandler.py
import xlrd
from settings import conf
class ExcelHandler(object):
def get_excel_data(self):
# 獲取到book對象
book = xlrd.open_workbook(conf.TEST_CASE_PATH)
# 獲取sheet對象
sheet = book.sheet_by_index(0)
rows, cols = sheet.nrows, sheet.ncols
l = []
title = sheet.row_values(0)
title.insert(0, 'i')
for i in range(1, rows):
values = sheet.row_values(i)
values.insert(0, i)
l.append(dict(zip(title, values)))
return l
demo.py
增加 @pytest.mark.parametrize,使測試用例參數化
from uti.ExcelHandler import ExcelHandler
...
@pytest.mark.parametrize('case', ExcelHandler().get_excel_data)
def test_demotest(self):
print(case['T1'])
...
當excel中包含了n條的記錄,則測試用例執行n次
進階:分布式運行測試用例
加入一個測試用例執行時間為10秒,那么如果excel中包含了60條記錄,那么就要執行10分鍾。
但是如果有10個進程同時執行這60個測試用例,那么執行時間就可以大大縮短。
所以這里引入了分布式運行用例插件pytest-xdist
安裝
pip install pytest-xdist
執行
pytest -n 10 demo.py --html=test_report.html
進階:報告中給錯誤用例截圖,並且顯示截圖
- 在項目的根目錄下創建conftest.py和__init__.py
- conftest.py
# coding=utf-8
import pytest
import time
import json
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
driver = None
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
dirpng = r'./report/png/'
file_name = dirpng + report.nodeid.replace("::", "_") + ".png"
file_path = os.path.split(file_name)[0] + '/'
if os.path.exists(file_path) and os.path.isdir(file_path):
pass
else:
os.makedirs(file_path)
file_name_in_report = r'./png/'+ report.nodeid.replace("::", "_")+".png"
_capture_screenshot(file_name)
if file_name:
html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % file_name_in_report
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot(name):
driver.get_screenshot_as_file(name)
@pytest.fixture(scope='session', autouse=True)
def browser():
global driver
if driver is None:
chrome_driver = r'C:\Users\L\AppData\Local\Google\Chrome\Application\chromedriver.exe' #chrome_driver 存放位置
chrome_options = Options()
chrome_options.add_argument('headless')
driver = webdriver.Chrome(executable_path=chrome_driver, options=chrome_options)
return driver
- 執行 pytest --html=report/report.html
- 在報告中,執行失敗的測試用例的右側將顯示截圖

Q&A
- 如果手動中止測試,是否會生成報告
可以。報告中會生成已經執行好的測試用例的結果。
- 如何重新執行失敗的用例?
pytest --lf demo.py --html=test_report_fail.html
- 當使用pytest執行時,如何顯示打印信息在控制台上?
加上-s參數。pytest -s demo.py --html=test_report.html
參考: pytest -- 捕獲標准輸出和標准錯誤輸出
- 當采用xdist並發運行后,即使加了-s,打印信息又不再顯示了
在代碼中加入sys.stdout = sys.stderr. 這樣執行后雖然控制台中顯示了,但是report中,打印信息又不再顯示
可以考慮在將print換成logging插件打印出log.
- 上面生成的報告,css是獨立的,分享報告的時候樣式會丟失,為了更好的分享發郵件展示報告,可以把css樣式合並到html里
pytest --html=report.html --self-contained-html
