在Python中使用pytest-selenium进行Web自动化测试的步骤如下:
- 安装pytest-selenium和selenium依赖库:
pip install pytest-selenium
pip install selenium
- 创建pytest测试用例文件(以test_example.py为例)并编写测试用例:
import pytest
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
@pytest.fixture(scope="function")
def firefox_browser(request):
from selenium.webdriver import Firefox, FirefoxProfile
profile = FirefoxProfile()
profile.set_preference("browser.startup.homepage",
"https://www.google.com/")
browser = Firefox(profile)
request.addfinalizer(lambda *args: browser.quit())
return browser
def test_google_search(firefox_browser):
firefox_browser.get('https://www.google.com/')
search_input = firefox_browser.find_element(By.NAME, 'q')
search_input.send_keys('pytest-selenium')
search_input.send_keys(Keys.RETURN)
result_div = firefox_browser.find_element(By.ID, 'search')
results = result_div.find_elements(By.TAG_NAME, 'a')
assert any('pytest' in r.text for r in results)
- 运行pytest进行测试:
pytest test_example.py
以上就是简单的pytest-selenium的测试用例编写和运行过程,可以根据自己的需求进行扩展。