python selenium wait方法
遇到一个网站运行很慢,所以要等待某个元素显示出来之后再进行操作,自己手上的书上没有例子可以直接用
发现一篇文章:http://www.cnblogs.com/yoyoketang/p/6517477.html 原文如下
前言:
在脚本中加入太多的sleep后会影响脚本的执行速度,虽然implicitly_wait()这种方法隐式等待方法一定程度上节省了很多时间。
但是一旦页面上某些js无法加载出来(其实界面元素经出来了),左上角那个图标一直转圈,这时候会一直等待的。
一、参数解释
1.这里主要有三个参数:
class WebDriverWait(object):driver, timeout, poll_frequency
2.driver:返回浏览器的一个实例,这个不用多说
3.timeout:超时的总时长
4.poll_frequency:循环去查询的间隙时间,默认0.5秒
以下是源码的解释文档(案例一个是元素出现,一个是元素消失)
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())
"""
二、元素出现:until()
1.until里面有个lambda函数,这个语法看python文档吧
2.以百度输入框为例
三、元素消失:until_not()
1.判断元素是否消失,是返回Ture,否返回False
备注:此方法未调好,暂时放这
四、参考代码:
# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
# 等待时长10秒,默认0.5秒询问一次
WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("kw")).send_keys("yoyo")
# 判断id为kw元素是否消失
is_disappeared = WebDriverWait(driver, 10, 1).\
until_not(lambda x: x.find_element_by_id("kw").is_displayed())
print is_disappeared
五、WebDriverWait源码
1.WebDriverWait主要提供了两个方法,一个是until(),另外一个是until_not()
以下是源码的注释,有兴趣的小伙伴可以看下
# 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)
python selenium wait方法的更多相关文章
- python+selenium安装方法
一.准备工具: 下载 python[python 开发环境] http://python.org/getit/ 下载 setuptools [python 的基础包工具] http://pypi.py ...
- python selenium webdriver方法封装(find_element_by)
下面是对find_element_by_就行了封装,封装之后的高级方法就是getElement() 下面是具体的代码: def getElement(self, selector): "&q ...
- Python+selenium自动化测试中Windows窗口跳转方法
Python+selenium自动化测试中Windows窗口跳转方法 #第一种方法 #获得当前窗口 nowhandle=driver.current_window_handle #打开弹窗 drive ...
- Python+Selenium定位元素的方法
Python+Selenium有以下八种定位元素的方法: 1. find_element_by_id() eg: find_element_by_id("kw") 2. find_ ...
- Python+Selenium自动化-定位一组元素,单选框、复选框的选中方法
Python+Selenium自动化-定位一组元素,单选框.复选框的选中方法 之前学习了8种定位单个元素的方法,同时webdriver还提供了8种定位一组元素的方法.唯一区别就是在单词elemen ...
- Python+Selenium自动化-设置等待三种等待方法
Python+Selenium自动化-设置等待三种等待方法 如果遇到使用ajax加载的网页,页面元素可能不是同时加载出来的,这个时候,就需要我们通过设置一个等待条件,等待页面元素加载完成,避免出现 ...
- Python+Selenium自动化-定位页面元素的八种方法
Python+Selenium自动化-定位页面元素的八种方法 本篇文字主要学习selenium定位页面元素的集中方法,以百度首页为例子. 0.元素定位方法主要有: id定位:find_elemen ...
- 一次完整的自动化登录测试-基于python+selenium进行cnblog的自动化登录测试
Web登录测试是很常见的测试!手动测试大家再熟悉不过了,那如何进行自动化登录测试呢!本文作者就用python+selenium结合unittest单元测试框架来进行一次简单但比较完整的cnblog自动 ...
- python selenium自动化(二)自动化注册流程
需求:使用python selenium来自动测试一个网站注册的流程. 假设这个网站的注册流程分为三步,需要提供比较多的信息: 在这个流程里面,需要用户填入信息.在下拉菜单中选择.选择单选的radio ...
随机推荐
- .NET:关于数据模型、领域模型和视图模型的一些思考
背景 数据模型.领域模型和视图模型是“模型”的三种角色,一些架构用一种类型表示这三种角色,如:传统三层架构.也有一些架构用两种类型表示这三种角色,如:结合ORM的领域驱动架构.非常少见的场景是用三种类 ...
- 《数据结构与算法图解》 分享 pdf下载
链接:https://pan.baidu.com/s/1gOMlwU5ucHYDVazvVMk2uw提取码:bk5x
- Shader Variants 打包遇到的问题
1. 遇到的问题 最常见的是打包到手机后效果与PC上不一致,具体情况比如: 光照贴图失效 雾失效 透明或者cutoff失效 以上首先需要检查的地方是Shader变体的编译设置 2. 超级着色器编译成N ...
- Unity3d — — UGUI之Box Collider自适应大小
NGUI下给Sprite/image添加collider后能自适应大小,但是在UGUI下Collider是默认在(0,0)位置,size为0 因此写了个简单的脚本,效果如下(最后附代码) 1.如下图添 ...
- RabbitMQ入门:Hello RabbitMQ 代码实例
在之前的一篇博客RabbitMQ入门:认识并安装RabbitMQ(以Windows系统为例)中,我们安装了RabbitMQ并且对其也有的初步的认识,今天就来写个入门小例子来加深概念理解并了解代码怎么实 ...
- Dubbo问题处理集合
1 . 启动微服务的时候,报错信息如下: 核心:Can not lock the registry cache file /root/.dubbo/dubbo-registry-127.0.0.1.c ...
- GitHub笔记(三)——分支管理和多人协作
三.分支管理 0 语句: 查看分支:git branch 创建分支:git branch <name> 切换分支:git checkout <name> 创建+切换分支:git ...
- HotSpot JVM 常用配置设置
本文讨论的选项是针对HotSpot虚拟机的. 1.选项分类及语法 HotspotJVM提供以下三大类选项: 1.1.标准选项 这类选项的功能是很稳定的,在后续版本中也不太会发生变化. 运行java或者 ...
- LeetCode 566. Reshape the Matrix (C++)
题目: In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a n ...
- Daily Scrum3 11.5
昨天的任务已经完成,但是大家分析后发现进度稍有些慢.今天各自都在调整进度,不再拖延别人的工作. 今日任务: 杨伊:做问卷调查,准备用户体验篇内容. 徐钧鸿:把Xueba中Utility 向闸瓦移植 张 ...