Python+Selenium自动化测试 5. 等待时间
目录
等待时间是我们做自动化测试时候的一个关键点,很多的页面跳转和加载都需要时间,假如我们没有设置等待时间,元素没有加载出来,那么程序就会报错,一个稳定的自动化测试代码肯定会有测试等待时间。
一 Python time模块的sleep
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox() #创建火狐对象
driver.get("https://www.baidu.com/") #打开baidu
sleep(5) #等待5毫秒
driver.quit() #关闭浏览器
一般不太推荐,因为这个是强制的等待,你设置了10S,它就会一直等待10S,假如你的脚本很多,那执行的时间和效率就会很慢,如何提升执行效率,其中我觉得有一点就是,少用sleep。
二 隐式等待
我们先看下源码:
设置粘滞超时以隐式等待找到元素,或完成命令。 此方法只需要调用一个每次会议的时间。 设置呼叫的超时时间execute_async_script,请参阅set_script_timeout。
:参数数量:
- time_to_wait:等待的时间(以秒为单位)
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) #这里设置智能等待10s
driver.get('https://www.baidu.com')
print (driver.title)
driver.quit()
总结:设置最长等待时长10S,如果10S内未找到元素则抛出NoSuchElementException异常,得不到某个元素就等待一段时间,直到拿到某个元素位置
Note:在使用隐式等待的时候,浏览器会在你自己设定的时间内部断的刷新页面去寻找我们需要的元素,它不影响我们的脚本的执行的速度。
三 显示等待
看源代码:
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method
IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method
class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.
:Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only.
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())
"""
self._driver = driver
self._timeout = timeout
self._poll = poll_frequency
# avoid the divide by zero
if self._poll == 0:
self._poll = POLL_FREQUENCY
exceptions = list(IGNORED_EXCEPTIONS)
if ignored_exceptions is not None:
try:
exceptions.extend(iter(ignored_exceptions))
except TypeError: # ignored_exceptions is not iterable
exceptions.append(ignored_exceptions)
self._ignored_exceptions = tuple(exceptions)
def __repr__(self):
return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(
type(self), self._driver.session_id)
def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace)
def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is False."""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message)
构造函数,获取WebDriver实例并在几秒钟内超时。
:参数数量:
- driver - WebDriver的实例(即,Firefox,Chrome或远程)
- timeout - 超时前的秒数
- poll_frequency - 呼叫之间的休眠间隔 (监测的时间间隔)
默认情况下,它是0.5秒。
- ignored_exceptions - 超时之后的报错。
默认情况下,它仅包含NoSuchElementException。
源代码中两个例子:等待10S,直到someID出现,用的是Python的匿名函数。
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId"))
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
例子:
引入包:
from selenium.webdriver.support.ui import WebDriverWait
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://www.baidu')
element = WebDriverWait(driver,5,0.5).util(
EC.presence_of_element_located((By.ID,'kw'))
)
element.send_keys('hello')
driver.quit()
根据判断条件而进行灵活进行处理时间等待问题,他会不断的根据你设定的条件去判断,直到超过你设置的等待时间。如果设置的条件满足,然后进行下一步操作,如果没有满足会报错。
总结:就是直到元素出现才去操作或者我们设定的条件满足才去操作,如果超时则报异常
四 总结:
- 隐式等待会在设定的时间内等driver完全加载完成;
- 显示等待仅仅校验需要加载的元素是否存在或者是否满足我们设定的条件;
- 强制等待就不管如何,一定要等待你设定的时间。