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总是屏蔽这篇文章,再加上最近 ...
随机推荐
- [Swift]LeetCode710. 黑名单中的随机数 | Random Pick with Blacklist
Given a blacklist B containing unique integers from [0, N), write a function to return a uniform ran ...
- 关于video标签移动端开发遇到的问题,获取视频第一帧,全屏,自动播放,自适应等问题
最近一直在处理video标签在IOS和Android端的兼容问题,其中遇到不少坑,绝大多数问题已经解决,下面是处理问题经验的总结: 1.获取视频的第一帧作为背景图: 技术:canvas绘图 windo ...
- [Abp 源码分析]八、缓存管理
0.简介 缓存在一个业务系统中十分重要,常用的场景就是用来储存调用频率较高的数据.Abp 也提供了一套缓存机制供用户使用,在使用 Abp 框架的时候可以通过注入 ICacheManager 来新建/设 ...
- Python内置函数(7)——bytearray
英文文档: class bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray cla ...
- 认识Junit基本注解@Before、@After、@Test、@BeforeClass、@AfterClass(转)
一.unit中集中基本注解,是必须掌握的. @BeforeClass – 表示在类中的任意public static void方法执行之前执行 @AfterClass – 表示在类中的任意public ...
- ECMAScript5.1的运算符、类型转换总结
一.运算符优先级 从高到低 运算符 说明 () 圆括号 . [] new(带参数列表) 字段访问.数组索引.new(带参数列表) () new(无参数列表) 函数调用,无参数列表 ++(后置递增) - ...
- asp.net core 系列 15 中间件
一.概述 中间件(也叫中间件组件)是一种装配到应用管道以处理请求和响应的软件. 每个组件:(1)选择是否将请求传递到管道中的下一个组件;(2)可以在管道中的下一个组件之前和之后执行工作. 请求委托用于 ...
- C#版 - 小红书后台开发面试题: 二维数组中的查找
二维数组中的查找 热度指数:24274 时间限制:1秒 空间限制:32768K 本题知识点: 查找 在线提交网址: http://www.nowcoder.com/practice/abc3fe2 ...
- google的GCM推送使用简介
pom <!-- https://mvnrepository.com/artifact/com.google.gcm/gcm-server --> <dependency> & ...
- 初学Java Web(6)——JSP学习总结
为什么要学习 JSP Servlet 的短板: Servlet 的出现,是为了解决动态输出网页的问题. 虽然这样做目的能达到,但是存在一些缺陷: 在 Servlet 输出网页片段非常恶心 (可读性差, ...