自动化测试selenium + python专题测试不止会点点点

Selenium2 Python实现中的Waits 等待api

2019-03-02  本文已影响13人  我爱泡澡堂

Selenium2 Python实现中的Waits 等待api

根据https://selenium-python.readthedocs.io/waits.html翻译和理解

前言

These days most of the web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNotVisibleException exception. Using waits, we can solve this issue. Waiting provides some slack between actions performed - mostly locating an element or any other operation with the element.

中文:
如今,大多数Web应用程序都使用Ajax技术。页面加载完成的时间变得长短不一(而且不可控),这使得定位元素变得困难:如果一个元素还没有出现在DOM中,定位方法就会抛出ElementNotVisibleException的异常。使用Waits,我们可以解决这个问题。在定位或者操作元素前我们可以提供一点一点的等待间隔时间。

Selenium Webdriver provides two types of waits - implicit & explicit. An explicit wait makes WebDriver wait for a certain condition to occur before proceeding further with execution. An implicit wait makes WebDriver poll the DOM for a certain amount of time when trying to locate an element.

中文:
Selenium WebDriver提供两种类型的等待-隐式和显式。显式等待使WebDriver在继续执行之前等待特定条件发生(理解为判定一个特定的条件成立)。隐式等待使WebDriver在尝试定位元素时对DOM进行一定时间的轮询(理解为不断刷新dom来尝试定位元素)。

一、显示方式(Explicit Waits)

An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

中文:
显示等待就是在执行之前定义一个特定的等待条件。最直接的方法是time.sleep(),它将设置的设定的等待时间参数作为等待条件。这里提供一些方便的方法帮助你编码来设定需要的等待时间。WebDriverWait与ExpectedCondition结合是实现这一目标的一种好的方案。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()

This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.

中文:
这段代码意思是等待10秒(s)钟直到找到需要的元素出现,超时的话会抛出TimeoutException异常。WebDriverWait默认每500毫秒(ms)调用一次预期条件(ExpectedCondition )的方法直到它返回成功。成功的条件是预期条件(ExpectedCondition )返回True或者非空。

预期条件(Expected Conditions)

There are some common conditions that are frequently of use when automating web browsers. Listed below are the names of each. Selenium Python binding provides some convenience methods so you don’t have to code an expected_condition class yourself or create your own utility package for them.

中文:
在做web浏览器自动化的时候,有一些条件是会经常被用到的。下面列举出了他们的名字。Selenium的Python提供了一些方便的方法,所以你不需要创建自己的预期条件类或者开发工具包。

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

The expected_conditions module contains a set of predefined conditions to use with WebDriverWait.

中文:
expected_conditions模块包含了一系列与WebDriverWait使用的预定义条件。

自定义等待条件(Custom Wait Conditions)

You can also create custom wait conditions when none of the previous convenience methods fit your requirements. A custom wait condition can be created using a class with call method which returns False when the condition doesn’t match.

中文
当预定义条件不满足你的需求的时候,可以自定义等待条件。当条件不满足的时候,自定义等待条件可以使用__call__ 方法返回False。

class element_has_css_class(object):
  """An expectation for checking that an element has a particular css class.
      一个通过检查CSS类的预期条件
  locator - used to find the element  查找条件
  returns the WebElement once it has the particular css class 返回含指定css类的WebElement 对象
  """
  def __init__(self, locator, css_class):
    self.locator = locator
    self.css_class = css_class

  def __call__(self, driver):
    element = driver.find_element(*self.locator)   # Finding the referenced element 定位条件的引用
    if self.css_class in element.get_attribute("class"):
        return element
    else:
        return False

# Wait until an element with id='myNewInput' has class 'myCSSClass'
# 等待直到找到id='myNewInput'  并且css类为'myCSSClass'的元素
wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))

二、隐式方式(Implicit Waits)

An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object.

中文:
隐式的方式会告诉WebDriver如果不能立刻找到指定的元素就以设定好的时间间隔去轮询DOM对像。默认的时间间隔是0,隐式等待间隔需要在WebDriver对象的生命周期中设置。

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds   在这里设置,单位秒(s)
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")

PS:本文中的中文翻译非直译,包含了本人的小理解,如果您觉得有重大错误,欢迎您给我留言

上一篇下一篇

猜你喜欢

热点阅读