selenium细节实战02-->好用的expected_conditions模块

本文介绍了Selenium库中的expected_conditions模块,它是用于网页元素状态判断的工具,常与WebDriverWait配合使用。通过示例展示了如何等待元素出现、可见、可点击等,并提供了unittest测试用例。此外,列举了多个expected_conditions的常用方法及其用法。

前言
行动是成功的阶梯,行动越多,登得越高。
不能懒,继续多更新分享一些给大家~~ 
一、expected_conditions模块是什么?
是Selenium的一个子模块,selenium.webdriver.support.expected_conditions
可以对网页上元素是否存在,可点击等等进行判断,一般用于断言或与WebDriverWait配合使用
二、expected_conditions模块简单应用
2.1 WebDriverWait与expected_conditions配合使用实例一


import os
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')

# 等待10s,等待过程中判断网页标题是否是"百度一下,你就知道"
# 如果是就继续执行后续代码,反之等待10s结束时报错
WebDriverWait(driver,10).until(EC.title_is("百度一下,你就知道"))

2.2 WebDriverWait与expected_conditions配合使用实例二


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
#等待10s,等待过程中如果定位到元素,就直接执行后续的代码,反之等待10s后报错误信息
element = WebDriverWait(driver,10).until(EC.visibility_of(driver.find_element(By.ID,'kw')))
element.send_keys( '新梦想软件测试' )


2.3 unittest与expected_conditions配合使用实例


import time
import unittest
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

class TestDemo(unittest.TestCase):
    def setUp(self) :
        self.driver = webdriver.Chrome()
    def tearDown(self):
        time.sleep(2)
        self.driver.quit()

    def test_searchinputbox_is_visibility(self):
        self.driver.get('https://www.baidu.com')
        #EC.visibility_of()判断元素是否可见,如果可见就返回这个元素 
        self.assertTrue(EC.visibility_of(self.driver.find_element(By.ID,'kw')))

if __name__=='__main__':
    unittest.main()

实例小结:

实例一与实例二中用到了显式等待 WebDriverWait类,该块不在此文中介绍;
实例三中self.assertTrue()方法断言括号内的表达式返回值是否为ture,在python中代表true的为 非0、非空、true,而EC.visibility_of()方法中的定位方法能定位到元素就会返回一个对象,满足非空为true,所以断言会通过;
注意EC.visibility_of()方法返回的对象非真实元素对象,所以不能执行如下代码:(正确方式参照实例二的写法)
element = EC.visibility_of(self.driver.find_element(By.ID,'kw'))
element.send_keys('newdream') 
三、expected_conditions模块用法汇总(不定期更新)

#判断当前页面的title是否精确等于预期,返回布尔值
WebDriverWait(driver,10).until(EC.title_is("百度一下,你就知道"))
#判断当前页面的title是否包含预期字符串,返回布尔值
WebDriverWait(driver,10).until(EC.title_contains('new'))
#判断当前页面的url是否精确等于预期,返回布尔值
WebDriverWait(driver,10).until(EC.url_contains('https://www.baidu.com'))
#判断当前页面的url是否包含预期字符串,返回布尔值
WebDriverWait(driver,10).until(EC.url_contains('baidu'))
#判断当前页面的url是否满足字符串正则表达式匹配,返回布尔值
WebDriverWait(driver,10).until(EC.url_matches('.+baidu.+'))
#判断元素是否出现,只要有一个元素出现,返回元素对象
WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID,'kw')))
#判断元素是否可见,返回元素对象
WebDriverWait(driver,10).until(EC.visibility_of(driver.find_element(By.ID,'kw')))
#判断元素是否包含指定文本,返回布尔值
WebDriverWait(driver,10).until(EC.text_to_be_present_in_element((By.NAME,'tj_trnews'),'新闻'))
#判断该frame是否可以switch进去,如果可以的话,返回True并且switch进去
WebDriverWait(driver,10,).until(EC.frame_to_be_available_and_switch_to_it(By.xpath,'//iframe'))
#判断某个元素是否可见并且是可点击的,如果是的就返回这个元素,否则返回False
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.NAME,'tj_trnews')))
#判断某个元素是否被选中,一般用在下拉列表
WebDriverWait(driver,10).until(EC.element_to_be_selected(driver.find_element(By.xpath,'//input[@type="checkbox"]')))
#判断页面上是否存在alert,如果有就切换到alert并返回alert的内容
WebDriverWait(driver,10).until(EC.alert_is_present())
#还有不少,用到了继续更新......

备注:以上整理大家要注意参数和返回值,部分参数是元素对象,部分是locator的元组,如(By.NAME,'tj_trnews')

### Selenium3 和 Python3 构建 Web 自动化测试框架:登录注册模块实现 Selenium 是一个强大的工具,用于跨平台和跨浏览器的端到端 Web 自动化测试[^1]。在构建基于 SeleniumPython 的自动化测试框架时,登录和注册模块是常见的测试场景之一。以下是一个详细的实现教程。 #### 1. 环境准备 在开始之前,确保已安装以下依赖项: - Python 3.x - Selenium 库(可通过 `pip install selenium` 安装) - 浏览器驱动(如 ChromeDriver 或 GeckoDriver) #### 2. 项目结构 为了组织代码,建议使用以下目录结构: ``` project/ │ ├── common/ # 公共模块 │ ├── config.py # 配置文件读取 │ └── test_runner.py # 测试执行器 │ ├── pages/ # 页面对象模型 (POM) │ ├── login_page.py # 登录页面逻辑 │ └── register_page.py # 注册页面逻辑 │ ├── tests/ # 测试用例 │ ├── test_login.py # 登录测试用例 │ └── test_register.py # 注册测试用例 │ └── report/ # 测试报告 ``` #### 3. 登录模块实现 以下是登录模块的实现步骤: ##### (1) `login_page.py` - 页面对象模型 ```python from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginPage: def __init__(self, driver): self.driver = driver self.url = "https://example.com/login" self.username_input = (By.ID, "username") self.password_input = (By.ID, "password") self.login_button = (By.ID, "login-btn") def open(self): self.driver.get(self.url) def enter_username(self, username): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.username_input) ).send_keys(username) def enter_password(self, password): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.password_input) ).send_keys(password) def click_login(self): WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(self.login_button) ).click() ``` ##### (2) `test_login.py` - 测试用例 ```python import unittest from selenium import webdriver from pages.login_page import LoginPage class TestLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path="path/to/chromedriver") self.login_page = LoginPage(self.driver) def test_valid_login(self): self.login_page.open() self.login_page.enter_username("valid_user") self.login_page.enter_password("valid_password") self.login_page.click_login() # 验证是否成功登录 title = self.driver.title self.assertIn("Dashboard", title) def tearDown(self): self.driver.quit() ``` #### 4. 注册模块实现 以下是注册模块的实现步骤: ##### (1) `register_page.py` - 页面对象模型 ```python from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class RegisterPage: def __init__(self, driver): self.driver = driver self.url = "https://example.com/register" self.email_input = (By.ID, "email") self.password_input = (By.ID, "password") self.confirm_password_input = (By.ID, "confirm-password") self.register_button = (By.ID, "register-btn") def open(self): self.driver.get(self.url) def enter_email(self, email): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.email_input) ).send_keys(email) def enter_password(self, password): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.password_input) ).send_keys(password) def enter_confirm_password(self, confirm_password): WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located(self.confirm_password_input) ).send_keys(confirm_password) def click_register(self): WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(self.register_button) ).click() ``` ##### (2) `test_register.py` - 测试用例 ```python import unittest from selenium import webdriver from pages.register_page import RegisterPage class TestRegister(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path="path/to/chromedriver") self.register_page = RegisterPage(self.driver) def test_valid_registration(self): self.register_page.open() self.register_page.enter_email("test@example.com") self.register_page.enter_password("securepassword123") self.register_page.enter_confirm_password("securepassword123") self.register_page.click_register() # 验证是否成功注册 success_message = self.driver.find_element(By.ID, "success-message").text self.assertEqual("Registration successful!", success_message) def tearDown(self): self.driver.quit() ``` #### 5. 执行测试 通过 `test_runner.py` 执行所有测试用例[^4]: ```python import time import unittest from HTMLTestRunner import HTMLTestRunner class TestRunner(object): def __init__(self, cases="../tests", title="Auto Test Report", description="Test case execution"): self.cases = cases self.title = title self.des = description def run(self): now = time.strftime("%Y-%m-%d_%H_%M_%S") fp = open(f"../report/{now}_result.html", 'wb') tests = unittest.defaultTestLoader.discover(self.cases, pattern='test*.py', top_level_dir=None) runner = HTMLTestRunner(stream=fp, title=self.title, description=self.des) runner.run(tests) fp.close() ``` 运行脚本后,生成的 HTML 报告将保存在 `report/` 目录中。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值