痛点:在页面查找元素的时候会遇到找不到或者其他无法处理某个字段的情况,又或者想要在输出的log或者report里面显示这个字段名称,这时候加上字段名称就很重要!
[3]python+selenium - UI自动框架之封装查找元素https://mp.csdn.net/mp_blog/creation/editor/139117915对上面一篇文章做优化
Element.py
from typing import Optional, Union
from selenium.common import TimeoutException, StaleElementReferenceException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from public.log import logclass ElementFinder(object):def __init__(self, driver: WebDriver):self._driver = driverdef find_element(self, by: Union[By, str], value: str, display_name: Optional[str] = None, time: int = 5, internal=0.5):_locator = (by, value)if display_name is None:display_name = valuefor _ in range(2):log.info('[100]:find element: {ele}'.format(ele=display_name))try:_element = WebDriverWait(self._driver, time, internal).until(ec.presence_of_element_located(_locator))return _elementexcept TimeoutException:log.exception('[400]:%s not find ' % display_name)except StaleElementReferenceException as e:log.exception('[401]:StaleElementReferenceException %s' % e)continueexcept NoSuchElementException as e:log.exception('[402]: NoSuchElement %s' % e)except Exception as e:log.exception('[403]:unknown error %s' % e)break
举个例子:
inputBox = ('id', 'kw','input box')searchBtn = ('id', 'su', 'search button')
Note:元素定位的时候,可以加上字段的’名称‘,当然也可以不加,这是一个非必要参数
相应地,在BasePage页面调用查找元素函数的时候也需要做改动,因为传给查找元素的参数多了一个字段。
[4]python+selenium - UI自动框架之封装基类BasePage页面https://mp.csdn.net/mp_blog/creation/editor/140102485只对basePage里面的一个功能做改动,其他类似要自己手动改:
basePage.py
from selenium.common import WebDriverException
from public.elementFind import ElementFinder
from public.log import logclass BasePage(ElementFinder):def click(self, locator):_element = self.find_element(*locator)if not _element:log.warning('[400]element {ele} not exits'.format(ele=locator))for _ in range(2):try:_element.click()breakexcept WebDriverException as e:log.exception('[401]:click {ele} failed,{info}'.format(ele=locator, info=e))except Exception as e:log.warning('[404]:click {ele},unknown error:{error}'.format(ele=locator, error=e))raise 'StopTestCaseException'