(二)將普通的Selenium代碼封裝成POM模式
1拨匆、案例說(shuō)明:
這里只是提供一種封裝的思路饶氏,小伙伴們可以根據(jù)自己的實(shí)際情況嘹狞,按需封裝赂蠢。
以下是簡(jiǎn)單普通的登錄測(cè)試用例
# 1. 導(dǎo)入包
from selenium import webdriver
import time
# 2. 打開(kāi)谷歌瀏覽器(獲取瀏覽器操作對(duì)象)
driver = webdriver.Chrome()
# 3. 打開(kāi)快遞100網(wǎng)站
url = "https://sso.kuaidi100.com/sso/authorize.do"
driver.get(url)
time.sleep(3)
# 4. 登陸網(wǎng)站
driver.find_element_by_id("name").send_keys('xxxxxxxxxxx')
driver.find_element_by_id("password").send_keys('xxxxxx')
driver.find_element_by_id("submit").click()
time.sleep(3)
# 5. 關(guān)閉瀏覽器
driver.quit()
那我們?nèi)绾芜M(jìn)行一個(gè)改造升級(jí)呢?
2砰蠢、加入unittest測(cè)試框架
# 1. 導(dǎo)入包
from selenium import webdriver
import time
import unittest
# 定義測(cè)試類
class TestCaseLogin(unittest.TestCase):
def setUp(self) -> None:
"""
前置函數(shù)
用于打開(kāi)瀏覽器蓖扑,連接數(shù)據(jù)庫(kù),初始化數(shù)據(jù)等操作
"""
# 2. 打開(kāi)谷歌瀏覽器(獲取瀏覽器操作對(duì)象)
self.driver = webdriver.Chrome()
# 3. 打開(kāi)快遞100網(wǎng)站
url = "https://sso.kuaidi100.com/sso/authorize.do"
self.driver.get(url)
time.sleep(3)
def tearDown(self) -> None:
"""
后置函數(shù)
用于關(guān)閉瀏覽器台舱,斷開(kāi)數(shù)據(jù)庫(kù)連接赵誓,清理測(cè)試數(shù)據(jù)等操作
"""
# 5. 關(guān)閉瀏覽器
self.driver.quit()
def testLogin(self):
"""登陸測(cè)試用例"""
self.driver.find_element_by_id("name").send_keys('xxxxxxxxxxx')
self.driver.find_element_by_id("password").send_keys('xxxxxx')
self.driver.find_element_by_id("submit").click()
time.sleep(3)
if __name__ == '__main__':
unittest.main()
如果有不清楚unittest測(cè)試框架的小伙伴可以查看我以前的unittest測(cè)試框架博客有4篇,簡(jiǎn)單易懂柿赊。
3俩功、加入元素顯示等待
我們上邊的示例中,用的是固定的等待時(shí)間碰声,我們需要有話一下代碼的效率诡蜓,加入元素的顯示等待。
關(guān)于元素顯示等待請(qǐng)看:元素等待的使用
Seleniun的EC模塊:EC模塊的使用
# 1. 導(dǎo)入包
from selenium import webdriver
import time
import unittest
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 定義測(cè)試類
class TestCaseLogin(unittest.TestCase):
def setUp(self) -> None:
"""
前置函數(shù)
用于打開(kāi)瀏覽器胰挑,連接數(shù)據(jù)庫(kù)蔓罚,初始化數(shù)據(jù)等操作
"""
# 2. 打開(kāi)谷歌瀏覽器(獲取瀏覽器操作對(duì)象)
self.driver = webdriver.Chrome()
# 3. 打開(kāi)快遞100網(wǎng)站
url = "https://sso.kuaidi100.com/sso/authorize.do"
self.driver.get(url)
time.sleep(2)
def tearDown(self) -> None:
"""
后置函數(shù)
用于關(guān)閉瀏覽器,斷開(kāi)數(shù)據(jù)庫(kù)連接瞻颂,清理測(cè)試數(shù)據(jù)等操作
"""
# 5. 關(guān)閉瀏覽器
time.sleep(2)
self.driver.quit()
def testLogin(self):
"""登陸測(cè)試用例"""
# 編寫定位器
name_input_locator = ("id", "name")
passwd_input_locator = ("id", "password")
submit_button_locator = ("id", "submit")
# 等待元素出現(xiàn)在操作元素
WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located(name_input_locator))
WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located(passwd_input_locator))
WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located(submit_button_locator))
self.driver.find_element_by_id("name").send_keys('xxxxxxxxxxx')
self.driver.find_element_by_id("password").send_keys('xxxxxx')
self.driver.find_element_by_id("submit").click()
if __name__ == '__main__':
unittest.main()