Selenium 高阶应用之WebDriverWait 和 expected_conditions

上一篇 / 下一篇  2015-08-26 12:16:38 / 精华(2) / 置顶(2) / 个人分类:情感天地

Seleniium 是相当不错的一个第三方测试框架,可惜目前国内已经无法访问其官网(FQ可以)。

      不知道大家是否有认真查看过selenium 的api,我是有认真学习过的。selenium 的api中包含有WebDriverWait  和 expected_conditions这两个高级应用。

  下面先看WebDriverWait :

复制代码
1importtime2fromselenium.common.exceptionsimportNoSuchElementException3fromselenium.common.exceptionsimportTimeoutException45POLL_FREQUENCY = 0.5#How long to sleep inbetween calls to the method6IGNORED_EXCEPTIONS = (NoSuchElementException,)#exceptions ignored during calls to the method789classWebDriverWait(object):10def__init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):11"""Constructor, takes a WebDriver instance and timeout in seconds.1213:Args:14- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)15- timeout - Number of seconds before timing out16- poll_frequency - sleep interval between calls17By default, it is 0.5 second.18- ignored_exceptions - iterable structure of exception classes ignored during calls.19By default, it contains NoSuchElementException only.2021Example:22from selenium.webdriver.support.ui import WebDriverWait \n23element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n24is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n25until_not(lambda x: x.find_element_by_id("someId").is_displayed())26"""27self._driver =driver28self._timeout =timeout29self._poll =poll_frequency30#avoid the divide by zero31ifself._poll ==0:32self._poll =POLL_FREQUENCY33exceptions =list(IGNORED_EXCEPTIONS)34ifignored_exceptionsisnotNone:35try:36exceptions.extend(iter(ignored_exceptions))37exceptTypeError:#ignored_exceptions is not iterable38exceptions.append(ignored_exceptions)39self._ignored_exceptions =tuple(exceptions)4041defuntil(self, method, message=''):42"""Calls the method provided with the driver as an argument until the \43return value is not False."""44screen =None45stacktrace =None4647end_time = time.time() +self._timeout48whileTrue:49try:50value =method(self._driver)51ifvalue:52returnvalue53exceptself._ignored_exceptions as exc:54screen = getattr(exc,'screen', None)55stacktrace = getattr(exc,'stacktrace', None)56time.sleep(self._poll)57iftime.time() >end_time:58break59raiseTimeoutException(message, screen, stacktrace)6061defuntil_not(self, method, message=''):62"""Calls the method provided with the driver as an argument until the \63return value is False."""64end_time = time.time() +self._timeout65whileTrue:66try:67value =method(self._driver)68ifnotvalue:69returnvalue70exceptself._ignored_exceptions:71returnTrue72time.sleep(self._poll)73iftime.time() >end_time:74break75raiseTimeoutException(message)
复制代码

 哈哈,我始终相信贴出来总会有人看。WebDriverWait 类位于selenium.webdriver.support.ui下面的例子很简单,

Example:
from selenium.webdriver.support.ui import WebDriverWait \n
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
                 until_not(lambda x: x.find_element_by_id("someId").is_displayed())

WebDriverWait 里面主要有两个方法,一个是until和until_not

那么我们可以这样用:
WebDriverWait(driver, 10).until(lambdax: x.find_element_by_id("某个按钮")).click()

  意思就是在10秒内等待某个按钮被定位到,咱们再去点击。就是每隔0.5秒内调用一下until里面的表达式或者方法函数,要么10秒内表达式执行成功,要么10秒后

抛出超时异常。

然后我们再看expected_conditions:
复制代码
1fromselenium.common.exceptionsimportNoSuchElementException2fromselenium.common.exceptionsimportNoSuchFrameException3fromselenium.common.exceptionsimportStaleElementReferenceException4fromselenium.common.exceptionsimportWebDriverException5fromselenium.common.exceptionsimportNoAlertPresentException67"""8* Canned "Expected Conditions" which are generally useful within webdriver9* tests.10"""11classtitle_is(object):12"""An expectation for checking the title of a page.13title is the expected title, which must be an exact match14returns True if the title matches, false otherwise."""15def__init__(self, title):16self.title =title1718def__call__(self, driver):19returnself.title ==driver.title2021classtitle_contains(object):22"""An expectation for checking that the title contains a case-sensitive23substring. title is the fragment of title expected24returns True when the title matches, False otherwise25"""26def__init__(self, title):27self.title =title2829def__call__(self, driver):30returnself.titleindriver.title3132classpresence_of_element_located(object):33"""An expectation for checking that an element is present on the DOM34of a page. This does not necessarily mean that the element is visible.35locator - used to find the element36returns the WebElement once it is located37"""38def__init__(self, locator):39self.locator =locator4041def__call__(self, driver):42return_find_element(driver, self.locator)4344classvisibility_of_element_located(object):45"""An expectation for checking that an element is present on the DOM of a46page and visible. Visibility means that the element is not only displayed47but also has a height and width that is greater than 0.48locator - used to find the element49returns the WebElement once it is located and visible50"""51def__init__(self, locator):52self.locator =locator5354def__call__(self, driver):55try:56return_element_if_visible(_find_element(driver, self.locator))57exceptStaleElementReferenceException:58returnFalse5960classvisibility_of(object):61"""An expectation for checking that an element, known to be present on the62DOM of a page, is visible. Visibility means that the element is not only63displayed but also has a height and width that is greater than 0.64element is the WebElement65returns the (same) WebElement once it is visible66"""67def__init__(self, element):68self.element =element6970def__call__(self, ignored):71return_element_if_visible(self.element)7273def_element_if_visible(element, visibility=True):74returnelementifelement.is_displayed() == visibilityelseFalse7576classpresence_of_all_elements_located(object):77"""An expectation for checking that there is at least one element present78on a web page.79locator is used to find the element80returns the list of WebElements once they are located81"""82def__init__(self, locator):83self.locator =locator8485def__call__(self, driver):86return_find_elements(driver, self.locator)8788classtext_to_be_present_in_element(object):89"""An expectation for checking if the given text is present in the90specified element.91locator, text92"""93def__init__(self, locator, text_):94self.locator =locator95self.text =text_9697def__call__(self, driver):98try:99element_text =_find_element(driver, self.locator).text100returnself.textinelement_text101exceptStaleElementReferenceException:102returnFalse103104classtext_to_be_present_in_element_value(object):105"""106An expectation for checking if the given text is present in the element's107locator, text108"""109def__init__(self, locator, text_):110self.locator =locator111self.text =text_112113def__call__(self, driver):114try:115element_text =_find_element(driver,116self.locator).get_attribute("value")117ifelement_text:118returnself.textinelement_text119else:120returnFalse121exceptStaleElementReferenceException:122returnFalse123124classframe_to_be_available_and_switch_to_it(object):125"""An expectation for checking whether the given frame. is available to126switch to.  If the frame. is available it switches the given driver to the127specified frame.128"""129def__init__

TAG: Python python Selenium WebDriverWait

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-08  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 32853
  • 日志数: 10
  • 文件数: 3
  • 建立时间: 2012-07-03
  • 更新时间: 2016-10-26

RSS订阅

Open Toolbar