自学内容网 自学内容网

[4]python+selenium - UI自动框架之封装基类BasePage页面

这部分内容是页面上的一些基本操作

from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException, \
    StaleElementReferenceException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from common.KeyActions import *
from common.errors import StopTestCaseException, KTEC_WebDriverException
from selenium.webdriver.support.select import Select
from common.elementFinder import ElementFinder
from selenium.webdriver.common.keys import Keys
from common.log import *
import os, win32gui, win32con, time
from common.publicFunc import *

class BasePage(ElementFinder):
    """
    Second encapsulation based on Selenium
    """

    #
    # def __init__(self, driver):
    #     self.driver = drive

    def open(self, url):
        """ Open url, browser maximization"""
        self.driver.get(url)
        self.driver.maximize_window()

    def get_url(self):
        url = self.driver.current_url
        return url

    def open_tap(self, url):
        """open a new browser tap"""
        old_handles = self.get_window_handles()
        simulateKey('ctrl', 't')
        time.sleep(5)
        for _ in range(5):
            if len(self.get_window_handles()) > len(old_handles):
                break
            else:
                time.sleep(2)
        self.switch_to_window(self.get_window_handles()[len(old_handles)])
        self.driver.get(url)

    def close_tap(self):
        """close browser tap"""
        self.driver.close()

    def close_browser(self):
        """close browser"""
        self.driver.quit()

    def go_back(self):
        """go back"""
        self.driver.back()

    def refresh_(self):
        """refresh browser"""
        self.driver.refresh()

    def click(self, locator, isUpdated=False):
        """ click element"""
        # element = self.find_element_clickable(locator)
        element = self.find_element_clickable(locator)
        if not element:
            log.warning('[BS]_436:element{ele} not exist'.format(ele=locator))
            return
        for _ in range(2):
            log.info('[BS]_006:step --> click {ele} time={num}'.format(ele=locator, num=_ + 1))
            try:
                self.click_element(element)
                # if Mode().getBrowserType() is None or (Mode().getBrowserType() is not None and (Mode().getBrowserType()).lower()=='ie'):
                #     self.driver.execute_script("$(arguments[0]).click()", element)
                # else:
                #     self.click_element(element)
                break
            except KTEC_WebDriverException as e:
                log.warning('[BS]_434: click {ele} failed!,{info}'.format(ele=locator, info=e))
                time.sleep(1)
                element = self.find_element_clickable(locator)
            except Exception as e:
                log.warning('[BS]_444:click {ele},unknown error:{error}'.format(ele=locator, error=e))
                raise StopTestCaseException

    def right_click(self, driver, locator, isUpdated=False):
        """ click element"""
        time.sleep(1)
        # element = self.find_element_clickable(locator)
        element = self.find_element_clickable(locator)
        if not element:
            log.warning('[BS]_436:element{ele} not exist'.format(ele=locator))
            return
        for _ in range(2):
            log.info('[BS]_006:step --> click {ele} time={num}'.format(ele=locator, num=_ + 1))
            try:
                ActionChains(driver).context_click(element).perform()
                # if Mode().getBrowserType() is None or (Mode().getBrowserType() is not None and (Mode().getBrowserType()).lower()=='ie'):
                #     self.driver.execute_script("$(arguments[0]).click()", element)
                # else:
                #     self.click_element(element)
                break
            except KTEC_WebDriverException as e:
                log.warning('[BS]_434: click {ele} failed!,{info}'.format(ele=locator, info=e))
                time.sleep(1)
                element = self.find_element_clickable(locator)
            except Exception as e:
                log.warning('[BS]_444:click {ele},unknown error:{error}'.format(ele=locator, error=e))
                raise StopTestCaseException

    def click_element(self, element):
        log.info('[BS]_00601:step --> click_element')
        try:
            element.click()
            time.sleep(1)
        except StaleElementReferenceException:
            raise KTEC_WebDriverException('[BS]_element is not attached to the page document')
        except WebDriverException as e:
            raise KTEC_WebDriverException('[BS]_element would not receive the click!{error}'.format(error=e))
        except Exception as e:
            log.warning('[BS]_434:unknown error! {info}'.format(info=e))

    def click_by_coordinate(self, locator, xoffset=None, yoffset=None):
        '''click element by coordinate'''
        if xoffset is None or yoffset is None:
            element = self.find_element(locator)
            location = element.location
            xoffset = location['x']
            yoffset = location['y']
        ActionChains(self.driver).move_by_offset(xoffset, yoffset).click().perform()

    def input(self, locator, value, isClear=True):
        """ input text """
        if value is None: return
        element = self.find_element_clickable(locator, timeout=3)
        if not element: return
        if isClear:
            element.clear()
        element.send_keys(value)

    def scroll_element_into_view(self, locator):
        """Scrolls the element identified by ``locator`` into view."""
        element = self.find_element(locator)
        # Try/except can be removed when minimum required Selenium is 4.0 or greater.
        try:
            ActionChains(self.driver).move_to_element(element).perform()
        except AttributeError:
            log.warning('[BS]_Workaround for Selenium 3 bug.')
            element = element.wrapped_element
            ActionChains(self.driver).move_to_element(element).perform()

    def drag_and_drop(self, locator, target):
        """Drags the element identified by ``locator`` into the ``target`` element.

        The ``locator`` argument is the locator of the dragged element
        and the ``target`` is the locator of the target. See the
        `Locating elements` section for details about the locator syntax.

        Example:
        | `drag_and_drop(('css':'div#element'),('css':'div.target'))
        """
        element = self.find_element(locator)
        target = self.find_element(target)
        action = ActionChains(self.driver)
        action.click_and_hold(element)
        action.drag_and_drop(element, target).perform()

    def drag_and_drop_offset(self, locator, xoffset, yoffset):
        """Drags the element identified by ``locator`` into the ``target`` element.

        The ``locator`` argument is the locator of the dragged element
        and the ``target`` is the locator of the target. See the
        `Locating elements` section for details about the locator syntax.

        Example:
        | `drag_and_drop(('css':'div#element'),('css':'div.target'))
        """
        element = self.find_element(locator)
        action = ActionChains(self.driver)
        action.click_and_hold(element)
        action.drag_and_drop_by_offset(element, xoffset, yoffset).perform()

    def select_frame(self, locator):
        """Sets frame identified by ``locator`` as the current frame.

        See the `Locating elements` section for details about the locator
        syntax.

        Works both with frames and iframes. Use `Unselect Frame` to cancel
        the frame selection and return to the main frame.
        """
        log.info("[BS]_Selecting frame '%s'." % locator[1])
        element = self.find_element(locator)
        self.driver.switch_to.frame(element)

    def unselect_frame(self):
        """Sets the main frame as the current frame.

        In practice cancels the previous `Select Frame` call.
        """
        self.driver.switch_to.default_content()

    @property
    def current_url(self):
        return self.driver.current_url

    def wait_until_element_located_not_contains_text(self, locator, expectText, timeout=6, interval=0.5):
        """
        Determine whether the text in the element is not equal to the expected text
        :param expectText: expected text
        :return: the actual text
        """
        try:
            WebDriverWait(self.driver, timeout, interval) \
                .until_not(EC.text_to_be_present_in_element(locator, expectText))
            current_text = self.find_element_visible(locator).text
            return True, current_text
        except TimeoutException:
            return False, expectText

    def wait_until_element_located_contains_text(self, locator, expectText, timeout=6, interval=0.5):
        """
        Determine whether the text in the element is equal to the expected text
        :param expectText: expected text
        :return : the actual text
        """

        try:
            WebDriverWait(self.driver, timeout, interval) \
                .until(EC.text_to_be_present_in_element(locator, expectText))
            return True, expectText
        except TimeoutException:
            try:
                current_text = self.find_element_visible(locator).text
            except TimeoutException:
                log.warning('[BS]_431:%s not find!' % str(locator))
            else:
                return False, current_text

    def is_Element_Exist(self, locator, timeout=10, interval=0.5):
        try:
            WebDriverWait(self.driver, timeout, interval) \
                .until(EC.visibility_of_element_located(locator))
            return True
        except Exception:
            return False

    def get_page_source(self):
        return self.driver.page_source

    def get_cookies(self):
        """ get browser's cookies """
        return self.driver.get_cookies()

    def move_to_element(self, locator):
        """ Mouse over a visible element """
        element = self.find_element_visible(locator)
        ActionChains(self.driver).move_to_element(element).perform()

    def execute_script(self, js_command):
        """execute javascript"""
        try:
            self.driver.execute_script(js_command)
        except Exception as e:
            log.warning('[BS] excute failed %s' % e)

    def switch_to_alert_and_confirm(self):
        """switch to alert window"""
        self.driver.switch_to_alert().accept()

    def select_item_by_value(self, locator, value):
        log.info('[BS]_006:step --> select_item_by_value {ele},value={text}'.format(ele=locator, text=value))
        try:
            element = self.find_element_visible(locator)
            Select(element).select_by_value(value)
        except NoSuchElementException:
            log.warning('[BS]_433:%s not in select' % value)

    def select_item_by_index(self, locator, index):
        log.info('[BS]_006:step --> select_item_by_index {ele},index={text}'.format(ele=locator, text=index))
        try:
            element = self.find_element_visible(locator)
            Select(element).select_by_index(index)
        except NoSuchElementException as e:
            log.warning('[BS]_433:%s not in select' % index)

    def select_item_by_visible_text(self, locator, text):
        log.info('[BS]_006:step --> select_item_by_visible_text {ele},text={text}'.format(ele=locator, text=text))
        try:
            element = self.find_element_visible(locator)
            Select(element).select_by_visible_text(text)
        except NoSuchElementException:
            log.warning('[BS]_433:%s not in select' % text)

    def get_selected_item_text(self, locator):
        """Return the currently selected item of select element"""
        log.info('[BS]_006:step --> get_selected_item_text {ele}'.format(ele=locator))
        element = self.find_element(locator)
        try:
            selected_option = Select(element).first_selected_option
            return selected_option.text
        except TypeError:
            log.warning("[BS]_432:%s not find!" % str(locator))
        except NoSuchElementException:
            log.warning("[BS]_433:No options are selected in %s" % str(locator))

    def get_all_select_item(self, locator):
        """Returns all options in the select element"""
        for _ in range(2):
            log.info('[BS]_006:step --> get_all_select_item {ele}, time={num}'.format(ele=locator, num=_ + 1))
            try:
                element = self.find_element(locator)
                selected_options = Select(element).options
                if not selected_options:
                    break
                else:
                    for i in range(len(selected_options)):
                        selected_options[i] = selected_options[i].text
            except TypeError:
                log.warning("[BS]_432:%s not find!" % str(locator))
                break
            except StaleElementReferenceException:
                log.info(
                    '[BS]_00601:step --> element{ele} is not attached to the page document'.format(ele=locator))
                continue
        return selected_options

    def is_element_located_selected(self, locator):
        log.info('[BS]_006:step --> is_element_located_selected {ele}'.format(ele=locator))
        try:
            element = self.find_element_visible(locator)
            element.is_selected()
            return True
        except TimeoutException:
            log.warning('[BS]_431:%s not find!' % str(locator))
            return False

    def get_elements_value(self, locator, timeout=6, interval=0.5):
        """
        Returns the text value of multiple elements in the list variable
        """
        for _ in range(2):
            log.info('[BS]_006:step --> get_elements_text {ele}, time={num}'.format(ele=locator, num=_ + 1))
            result = []
            try:
                elements = self.find_elements(locator, timeout, interval)
                if elements is not None:
                    for ele in elements:
                        result.append(ele.text)
                return result
            except AttributeError:
                log.warning('[BS]_431:%s not find!' % str(locator))
                break
            except StaleElementReferenceException:
                log.info(
                    '[BS]_00601:step --> elements{ele} is not attached to the page document'.format(ele=locator))
                time.sleep(1)
                continue

    def get_element_text(self, locator, timeout=6, interval=0.5):
        """ Return the text value of the element"""
        for _ in range(2):
            log.info('[BS]_006:step --> get_element_text {ele}, time={num}'.format(ele=locator, num=_ + 1))
            try:
                element = self.find_element(locator, timeout, interval)
                return element.text
            except AttributeError:
                log.warning('[BS]_431:%s not find!' % str(locator))
                break
            except StaleElementReferenceException:
                log.info(
                    '[BS]_00601:step --> element{ele} is not attached to the page document'.format(ele=locator))
                time.sleep(1)
                continue

    def get_element_Attribute_value(self, locator, attribute, timeout=6, interval=0.5):
        """
        Get an attribute value of an element
        For example:
        get_element_Attribute_value(locator=('id','xxx'),attribute='class')
        """
        for _ in range(2):
            log.info(
                '[BS]_006:step --> get_element_Attribute_value {ele}, time={num}'.format(ele=locator, num=_ + 1))
            try:
                element = self.find_element(locator, timeout, interval)
                try:
                    attributeValue = element.get_attribute(attribute)
                    return attributeValue
                except Exception as e:
                    log.warning(
                        '431:can not get attribute [%s] value and error message is %s !' % (str(attribute), str(e)))
                    break
            except AttributeError:
                log.warning('[BS]_431:%s not find!' % str(locator))
                break
            except StaleElementReferenceException:
                log.info(
                    '[BS]_00601:step --> element{ele} is not attached to the page document'.format(ele=locator))
                time.sleep(1)
                continue

    def checkbox_is_selected(self, locator, timeout=3, interval=0.5):
        """get whether checkbox is selected"""
        log.info('[BS]_006:step --> checkbox_is_selected {ele}'.format(ele=locator))
        try:
            WebDriverWait(self.driver, timeout, interval) \
                .until(EC.element_located_to_be_selected(locator))
            return True
        except TimeoutException:
            return False

    def checkbox_is_not_selected(self, locator, timeout=3, interval=0.5):
        """get whether checkbox is not selected"""
        log.info('[BS]_006:step --> checkbox_is_not_selected {ele}'.format(ele=locator))
        try:
            WebDriverWait(self.driver, timeout, interval) \
                .until_not(EC.element_located_to_be_selected(locator))
            return True
        except TimeoutException:
            return False

    def is_visible(self, locator, timeout=1, interval=0.5):
        """ Judge whether the element is visible """
        log.info('[BS]_006:step --> is_visible {ele}'.format(ele=locator))
        try:
            WebDriverWait(self.driver, timeout, interval).until(EC.visibility_of_element_located(locator))
            isdisplay = True
        except TimeoutException:
            isdisplay = False
        return isdisplay

    def is_clickable(self, locator, timeout=1, interval=0.5):
        """ Judge whether the element is visible """
        log.info('[BS]_006:step --> is_clickable {ele}'.format(ele=locator))
        try:
            WebDriverWait(self.driver, timeout, interval).until(EC.element_to_be_clickable(locator))
            isdisplay = True
        except TimeoutException:
            isdisplay = False
        return isdisplay

    def is_enable(self, locator):
        log.info('[BS]_006:step --> is_enable {ele}'.format(ele=locator))
        try:
            result = self.find_element(locator).is_enabled()
        except TypeError:
            return None
        return result

    def dismiss_alert(self):
        """dismiss alert"""
        self.driver.switch_to_alert().dismiss()

    def accept_alert(self):
        """Accept alert"""
        self.driver.switch_to_alert().accept()

    def curr_window_handle(self):
        """Get current window handle"""
        handle = self.driver.current_window_handle
        return handle

    def get_window_handles(self):
        """Get handles of all currently open windows"""
        handles = self.driver.window_handles
        return handles

    def switch_to_window(self, handle):
        """switch to window"""
        self.driver.switch_to.window(handle)

    def sendSpace(self, locator):
        """Enter SAPCE in the current element"""
        self.sendKeys(locator, Keys.SPACE)

    def sendEnter(self, locator):
        """Enter ENTER in the current element"""
        self.sendKeys(locator, Keys.ENTER)

    def sendFile(self, locator, path):
        element = self.find_element(locator)
        element.send_keys(path)

    def take_screenshot(self, screen_dir, fileName=None):
        '''
        screenshot
        For example:
        take_screenshot(screen_dir="C:\\forder",fileName="screenshot.png")
        '''
        rq = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))

        if fileName is None:
            fileName = rq
        else:
            fileName = fileName + "_" + rq

        file_extension = fileName.rsplit(".", 1)
        if len(file_extension) == 2:
            if not file_extension[1].lower() in ['png', 'jpg', 'jpeg']:
                fileName = fileName + '.png'
        else:
            fileName = fileName + '.png'

        screen_name = os.path.join(screen_dir, fileName)
        try:
            self.driver.get_screenshot_as_file(screen_name)
            log.info("[BS]_Had take screenshot and saved!")
        except Exception as e:
            log.error("[BS]_Failed to take screenshot!", format(e))

    def upload_file(self, locator, filepath):
        self.click(locator)
        try:
            if filepath is not None:
                try:
                    dialog = win32gui.FindWindow('#32770', 'Open')  # 对话框
                    ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, "ComboBoxEx32", None)
                    ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, "ComboBox", None)
                    edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None)  # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄
                    button = win32gui.FindWindowEx(dialog, 0, 'Button', None)  # 确定按钮Button
                    win32gui.SendMessage(edit, win32con.WM_SETTEXT, None, filepath)  # 往输入框输入绝对地址
                    win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)  # 按button
                except Exception as e:
                    log.error("[BS]_Failed to upload fileFormat!", format(e))
        except Exception as e:
            log.error(("[BS]_filepath is empty!", format(e)))

    def reset_Attribute(self, locator, attribute, value):
        try:
            element = self.find_element(locator)
            self.driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])", element, attribute,
                                       value)
        except Exception as e:
            log.error(("[BS]_attribute is not found!", format(e)))

    def wait_until_disappear(self, locator, waitTime=5):
        name = get_variable_name(locator)
        for _ in range(5):
            if self.is_visible(locator, waitTime):
                time.sleep(waitTime)
                log.info("waiting %s disappear" % name)
            else:
                log.info("waited %s disappear" % name)
                break

    def wait_element_visible(self, locator, waitTime=2):
        for _ in range(5):
            if self.is_visible(locator, waitTime):
                break
            else:
                time.sleep(waitTime)
                log.info("[BS]_wait element is visible")

    def get_AttributeValue(self, locator, attribute):
        try:
            element = self.find_element(locator)
            value = element.get_addribute(attribute)
            return value
        except Exception as e:
            log.error(("[BS]_locator is not found!", format(e)))



if __name__ == "__main__":
    '''self test'''


原文地址:https://blog.csdn.net/weixin_41708323/article/details/140102485

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!