摘自https://www.cnblogs.com/sanzangTst/p/8376221.html

当你觉得你的定位没有问题,但是却直接报了元素不可见,那你就可以考虑是不是因为程序运行太快或者页面加载太慢造成了元素不可见,那就必须要加等待了,等待元素可见再继续运行程序。

一、强制等待(sleep)

设置等待最简单的方法就是强制等待,其实就是time.sleep()方法,不管它什么情况,让程序暂停运行一定时间,时间过后继续运行;缺点时不智能,设置的时间太短,元素还没有加载出来,那照样会报错;设置的时间太长,则会浪费时间,不要小瞧每次几秒的时间,case多了,代码量大了,很多个几秒就会影响整体的运行速度了。

二、隐性等待(implicitly_wait())

driver.implicitly_wait(),隐性等待设置了一个时间,在一段时间内网页是否加载完成,如果完成了,就进行下一步;在设置的时间内没有加载完成,则会报超时加载。

缺点是不智能,因为随着ajax技术的广泛应用,页面的元素往往都可以时间局部加载,也就是在整个页面没有加载完的时候,可能我们需要的元素已经加载完成了,那就么有必要再等待整个页面的加载,执行进行下一步,而隐性等待满足不了这一点;

  另外一点,隐性等待的设置时全局性的,在开头设置过之后,整个的程序运行过程中都会有效,都会等待页面加载完成;不需要每次设置一遍;

三、显性等待(WebDriverWait)

WebDriverWait(driver, 20, 0.5).until(expected_conditions.presence_of_element_located(locator)),selenium中的wait模块的WebDriverWait()方法,配合until或者until_not方法,再辅助以一些判断条件,就可以构成这样一个场景:每经过多少秒就查看一次locator的元素是否可见,如果可见就停止等待,如果不可见就继续等待直到超过规定的时间后,报超时异常;当然也可以判断某元素是否在规定时间内不可见等等的各种场景吧,需要根据你自己实际的场景选择判断条件。

expected_conditions模块中提供了很多可以提供判断的条件:

text_to_be_present_in_element

text_to_be_present_in_element_value

#这个条件判断frame是否可切入,可传入locator元组或者直接传入定位方式:id、name、index或WebElement

frame_to_be_available_and_switch_to_it

# 这个条件判断是否有alert出现

alert_is_present

# 这个条件判断元素是否可点击,传入locator

element_to_be_clickable

# 这四个条件判断元素是否被选中,第一个条件传入WebElement对象,第二个传入locator元组

# 第三个传入WebElement对象以及状态,相等返回True,否则返回False

# 第四个传入locator以及状态,相等返回True,否则返回False

element_to_be_selected

element_located_to_be_selected

element_selection_state_to_be

element_located_selection_state_to_be

# 最后一个条件判断一个元素是否仍在DOM中,传入WebElement对象,可以判断页面是否刷新

staleness_of

四、WebDriverWait源码

# 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)

自动化测试基础篇--Selenium等待时间的更多相关文章

  1. 自动化测试基础篇--Selenium简单的163邮箱登录实例

    摘自https://www.cnblogs.com/sanzangTst/p/7472556.html 前面几篇内容一直讲解Selenium Python的基本使用方法.学习了什么是selenium: ...

  2. 自动化测试基础篇--Selenium文件上传send_keys

    摘自https://www.cnblogs.com/sanzangTst/p/8358165.html 文件上传是web页面上很常见的一个功能,自动化成功中操作起来却不是那么简单. 一般分两个场景:一 ...

  3. 自动化测试基础篇--Selenium鼠标键盘事件

    摘自https://www.cnblogs.com/sanzangTst/p/7477382.html 前面几篇文章我们学习了怎么定位元素,同时通过实例也展示了怎么切换到iframe,怎么输入用户名和 ...

  4. 自动化测试基础篇--Selenium元素定位

    摘自https://www.cnblogs.com/sanzangTst/p/7457111.html 一.Selenium元素定位的重要性: Web自动化测试的操作:获取UI页面的元素,对元素进行操 ...

  5. 自动化测试基础篇--Selenium简介

    摘自https://www.cnblogs.com/sanzangTst/p/7452636.html 一.软件开发的一般流程 二.什么叫软件测试? 软件测试(英语:Software Testing) ...

  6. 自动化测试基础篇--Selenium Python环境搭建

    学习selenium python需要的工具: 1.浏览器 2.Python 3.Selenium 4.FireBug(Firefox) 5.chromedriver.IEDriverServer.g ...

  7. 引用 自动化测试基础篇--Selenium简介

    原文链接:http://www.cnblogs.com/sanzangTst/p/7452636.html 鸣谢参藏法师 一.软件开发的一般流程 二.什么叫软件测试? 软件测试(英语:Software ...

  8. 引用 自动化测试基础篇--Selenium Python环境搭建

    原文链接:https://www.cnblogs.com/sanzangTst/p/7452922.html 鸣谢参藏法师. 学习selenium python需要的工具: 1.浏览器 2.Pytho ...

  9. 自动化测试基础篇--Selenium框架设计(POM)

    一.自动化测试框架 感谢木棉花的漂泊分享,内容转自链接:http://www.cnblogs.com/fengyiru6369/p/8053035.html 1.什么是自动化测试框架 简单来说,自动化 ...

随机推荐

  1. [NewLife.XCode]高级查询(化繁为简、分页提升性能)

    NewLife.XCode是一个有10多年历史的开源数据中间件,支持nfx/netcore,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量结合示例代码和 ...

  2. C# 获取 sha256

    C# 获取 sha256, 输入可以是 字符串,也可以是 字节流流: 自定义的输入类型的枚举: public enum Sha26ParseType { StringType, StreamType ...

  3. go跨平台编译

    go语言支持直接编译不同系统的可执行程序,例如可以直接在mac上可以直接编译linux的执行程序 支持的环境变量 GOOS:目标可执行程序运行操作系统,支持 darwin,freebsd,linux, ...

  4. [CF286E] Ladies' shop

    Description 给出 \(n\) 个 \(\leq m\) 且不同的数 \(a_1,\dots,a_n\),现在要求从这 \(n\) 个数中选出最少的数字,满足这 \(n\) 个数字都可以由选 ...

  5. 基于SpringMVC+Spring+MyBatis实现秒杀系统【数据库接口】

    前言 该篇教程主要关注MyBatis实现底层的接口,把MyBatis交给Spring来托管.数据库连接池用的c3p0.数据库用的MySQL.主要有2个大类:秒杀商品的查询.秒杀明细的插入. 准备工作 ...

  6. UVC 驱动调用过程与驱动框架的简单分析

    内核:Linux-3.4.2 驱动:drivers\media\video\uvc\uvc_driver.c UVC 驱动整体调用流程: /* 打开设备描述符 */ 1. open: uvc_v4l2 ...

  7. 实战!基于lamp安装Discuz论坛-技术流ken

    简介 我前面的博客已经详细介绍了lamp采用yum安装以及编译安装的方式,这篇博客将基于yum安装的lamp架构来实战安装Discuz论坛,你可以任选其一来完成. 系统环境 centos7.5 服务器 ...

  8. 阿里云免费SSL证书申请与安装使用(IIS7)

    准备: 阿里云已完成备案的域名一个 第一步:免费SSL证书申请 登陆阿里云平台,在域名控制台下,选择你的域名,点击“SSL”证书,如图所示 再跳转后的页面,选择“单域名免费证书”,并补全域名,非二级域 ...

  9. 依然是关于我空间那篇申请的日志《JavaScript axError:Unexpected token ILLEGAL 很简单的代码……》

    接下来要讲的日志现在的标题已经更改为<很简单的代码,但是无法--> 这篇日志地址:http://www.cnblogs.com/herbertchina/p/4475092.html 经过 ...

  10. Centos 6.8 定时任务Crontab服务

    一,crontab服务的简介 二.安装cron服务 安装cron服务 : --yum install vixie-cron --yum install crontabs 检出cron服务 检查cron ...