selenium-判断元素是否可见(五)
很多 case 在运行时都会出现页面还没加载完成,但是脚本已经跑完,并且报未找到元素
这是就需要增加判断,在预定的时间内如果页面显示了某元素后再让脚本继续执行,则为判断元素是否可见或者说页面是否显示了某元素
以百度首页,搜素框为例:
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
baidu_input = driver.find_element_by_id('kw')
EC.visibility_of_element_located(baidu_input) driver.close()
EC.visibility_of_element_located(baidu_input) 只是判断元素是否可见,若果这样写明显存在不合理的地方。如果代码运行很快,页面还未加载完就会出现该元素可见找不到。
所以通常需要结合 WebDriverWait 一起使用
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')
baidu_input = (By.ID, 'kw')
WebDriverWait(driver,10).until(EC.visibility_of_element_located(baidu_input)) driver.close()
查看 WebDriverWait 类,他需要传入driver,超时时间timeout,而 unit 只需要传入定位元素,如下代码 WebDriverWait 类所示
所以在使用 WebDriverWait 时需要对元素定位使用 By 定位,剔除通过 driver 再定位的方法,如上代码所示
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)
元素是否可见的方法
visibility_of_element_located : 判断某个元素是否可见
invisibility_of_element_located : 判断某个元素是否不存在或不可见
visibility_of : 判断元素是否可见,通过 driver 查找元素,如:EC.visibility_of(driver.find_element_by_id('kw'))
visibility_of_all_elements_located() :判断定位的所有元素都存在于DOM树中并且可见,可存在则以list形式返回
visibility_of_any_elements_located() : 判断定位的所有元素中,至少有一个存在于DOM树中并且可见,list形式返回存在的元素
selenium-判断元素是否可见(五)的更多相关文章
- python selenium判断元素是否存在的问题
爬虫的时候经常用到这个,找到了一个比较好用的方法 原文链接:http://blog.csdn.net/u012189659/article/details/36391837 背景:selenium+p ...
- 自动化测试基础篇--Selenium判断元素是够存在
摘自https://www.cnblogs.com/sanzangTst/p/8376101.html selenium+python处于学习阶段,功能实现之后开始整理之前写的代码,突然发现一个功能没 ...
- selenium判断元素类型
在做级联的下拉框时发现第一次选择了下拉框(如省份),第二个下拉框可能是输入框,也可能是下拉框,这个时候就需要判断他的元素类型,来做判断 图1 图2 原理很简单:获取控件的html文件内容,拿到内容后在 ...
- selenium在操作隐藏元素时会报错,怎么判断元素是隐藏的?
首先页面元素隐藏有五种方法: 1. opacity: 0; opacity 属性的意思是设置一个元素的透明度.它不是为改变元素的边界框(bounding box)而设计的.这意味着将 opacity ...
- selenium常用的API(七)判断元素是否可见
web页面不可见的元素虽不在页面上显示,但是存在于DOM树中,这些元素webdriver也能找到. element.is_displayed()方法可以判断元素是否在页面上显示,如果显示返回True, ...
- 《手把手教你》系列技巧篇(十五)-java+ selenium自动化测试-元素定位大法之By xpath中卷(详细教程)
1.简介 按宏哥计划,本文继续介绍WebDriver关于元素定位大法,这篇介绍定位倒数二个方法:By xpath.xpath 的定位方法, 非常强大. 使用这种方法几乎可以定位到页面上的任意元素. ...
- 《手把手教你》系列技巧篇(四十七)-java+ selenium自动化测试-判断元素是否显示(详解教程)
1.简介 webdriver有三种判断元素状态的方法,分别是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的内容中已经简单的介绍了,isSelec ...
- 《手把手教你》系列技巧篇(四十八)-java+ selenium自动化测试-判断元素是否可操作(详解教程)
1.简介 webdriver有三种判断元素状态的方法,分别是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的内容中已经简单的介绍了,isSelec ...
- Selenium判断获取的元素是否可见(display:none)
在爬虫中需要自动登陆并判断是否登陆成功,如果登陆错误的话还需要知道错误提示信息,此时需要判断提示信息是否可见 if self.element_exist_xpath('//*[@id="bu ...
- [python爬虫] Selenium常见元素定位方法和操作的学习介绍
这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~同时CSDN总是屏蔽这篇文章,再加上最近 ...
随机推荐
- IDEA激活码(2019)
如您激活出现问题,请点击这里加入:软件激活问题解决群 前言 IDEA已然成为我最热爱的一款编辑器,作为一个从Eclipse阵营转过来的coder,确实能感受到IDEA的强大,而我电脑桌面的Eclips ...
- Oracle绝对秒数转换为时间戳
一般Oracle得到的时间格式为: 1970-01-05 01:23:56.297 为了计算两个时间的差值: 1970-01-05 01:23:56.297 与 1970-01-05 01:24:57 ...
- 【Spark篇】---Spark故障解决(troubleshooting)
一.前述 本文总结了常用的Spark的troubleshooting. 二.具体 1.shuffle file cannot find:磁盘小文件找不到. 1) connection timeout ...
- "无需开发经验" 也能拥有小程序
本文分享嘉宾:毛帅,又拍图片管家资深开发工程师,主要负责又拍图片管家.图管小程序第三方平台.图管小程序等项目的开发.维护及拓新工作.熟悉 JS / C++ 等语言,有丰富的 NodeJS 开发经验,热 ...
- java代码之美(8)---guava字符串工具
guava字符串工具 在java开发过程中对字符串的处理是非常频繁的,google的guava工具对字符串的一些处理进行优化,使我们开发过程中让自己的代码看去更加美观,清爽. 一.Joiner 根据给 ...
- 知其所以然~tcp和udp的区别
TCP UDP TCP与UDP基本区别 基于连接与无连接 TCP要求系统资源较多,UDP较少: UDP程序结构较简单 流模式(TCP)与数据报模式(UDP); TCP保证数据正确性,UDP可能丢包 T ...
- flag.xls
Topic Link http://ctf5.shiyanbar.com/misc/flag.xls 1) 打开表格发现需要密码 但是flag又在表里,但我们可以改他的格式为.txt文本,因为这样就 ...
- Java开发知识之Java字符串类
Java开发知识之Java字符串类 一丶简介 任何语言中.字符串都是很重要的.都涉及到字符串的处理. 例如C++中. 字符串使用内存. 并提供相应的函数进行处理 strcmp strcat strcp ...
- [解决方案]SystemError: Parent module '' not loaded, cannot perform relative import的解决方案
缺陷:__mian__不能使用相对导入 PEP 328 Relative Imports and __name__ 中说明: Relative imports use a module's __nam ...
- 附实例!图解React的生命周期及执行顺序
本文由云+社区发表 作者:前端林子 1.七个可选的生命周期 可以结合下图来看: (1) componentWillMount() 仅在render()方法前被调用一次,如果在该方法中调用了setSta ...