二次封裝WebDriverWait

雾以丶泪聚發表於2024-08-26

查詢web頁面元素時,經常會有元素需要時間載入出來,使用WebDriverWait顯示等待,但是語法過於複雜,所以進行二次封裝。

封裝前:
ele1 = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("account"))

二次封裝:

from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait


class Base:

    def __init__(self, driver):
        self.driver = driver  # 瀏覽器物件
        self.timeout = 10  # 超時時間
        self.cycle = 0.5  # 元素查詢間隙時間

    def __findElement(self, locator) -> WebElement:
        """
        私有方法:查詢元素
        :param locator: 定位器,使用方法locator:(By.ID, 'kw')
        :return: element
        """
        element = WebDriverWait(self.driver, self.timeout, self.cycle, None).until(lambda x: x.find_element(*locator))
        return element

    def sendKeys(self, locator, text):
        ele = self.__findElement(locator)
        ele.send_keys(text)

    def click(self, locator):
        ele = self.__findElement(locator)
        ele.click()

    def clear(self, locator):
        ele = self.__findElement(locator)
        ele.clear()

上面只封裝了常用的三個方法,如果需要也可以封裝其它元素操作方法。
以一個登入操作為例,二次封裝後呼叫:

"""
公共的登入函式
"""
from . import base
from selenium import webdriver
from selenium.webdriver.common.by import By


class LoginZenTao:

    def __init__(self, driver: webdriver):
        self.driver = driver
        self.base = base.Base(self.driver)

    def login(self, username='admin', password='123456') -> None:
        """
        登入函式
        :param username: 賬號
        :param password: 密碼
        :return: None
        """
        account_loc = (By.ID, 'account')
        psw_loc = (By.NAME, 'password')
        sub_loc = (By.ID, 'submit')
        self.base.sendKeys(account_loc, username)
        self.base.sendKeys(psw_loc, password)
        self.base.click(sub_loc)

相關文章