很多 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-判断元素是否可见(五)的更多相关文章

  1. python selenium判断元素是否存在的问题

    爬虫的时候经常用到这个,找到了一个比较好用的方法 原文链接:http://blog.csdn.net/u012189659/article/details/36391837 背景:selenium+p ...

  2. 自动化测试基础篇--Selenium判断元素是够存在

    摘自https://www.cnblogs.com/sanzangTst/p/8376101.html selenium+python处于学习阶段,功能实现之后开始整理之前写的代码,突然发现一个功能没 ...

  3. selenium判断元素类型

    在做级联的下拉框时发现第一次选择了下拉框(如省份),第二个下拉框可能是输入框,也可能是下拉框,这个时候就需要判断他的元素类型,来做判断 图1 图2 原理很简单:获取控件的html文件内容,拿到内容后在 ...

  4. selenium在操作隐藏元素时会报错,怎么判断元素是隐藏的?

    首先页面元素隐藏有五种方法: 1. opacity: 0; opacity 属性的意思是设置一个元素的透明度.它不是为改变元素的边界框(bounding box)而设计的.这意味着将 opacity ...

  5. selenium常用的API(七)判断元素是否可见

    web页面不可见的元素虽不在页面上显示,但是存在于DOM树中,这些元素webdriver也能找到. element.is_displayed()方法可以判断元素是否在页面上显示,如果显示返回True, ...

  6. 《手把手教你》系列技巧篇(十五)-java+ selenium自动化测试-元素定位大法之By xpath中卷(详细教程)

    1.简介 按宏哥计划,本文继续介绍WebDriver关于元素定位大法,这篇介绍定位倒数二个方法:By xpath.xpath 的定位方法, 非常强大.  使用这种方法几乎可以定位到页面上的任意元素. ...

  7. 《手把手教你》系列技巧篇(四十七)-java+ selenium自动化测试-判断元素是否显示(详解教程)

    1.简介 webdriver有三种判断元素状态的方法,分别是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的内容中已经简单的介绍了,isSelec ...

  8. 《手把手教你》系列技巧篇(四十八)-java+ selenium自动化测试-判断元素是否可操作(详解教程)

    1.简介 webdriver有三种判断元素状态的方法,分别是isEnabled,isSelected 和 isDisplayed,其中isSelected在前面的内容中已经简单的介绍了,isSelec ...

  9. Selenium判断获取的元素是否可见(display:none)

    在爬虫中需要自动登陆并判断是否登陆成功,如果登陆错误的话还需要知道错误提示信息,此时需要判断提示信息是否可见 if self.element_exist_xpath('//*[@id="bu ...

  10. [python爬虫] Selenium常见元素定位方法和操作的学习介绍

    这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~同时CSDN总是屏蔽这篇文章,再加上最近 ...

随机推荐

  1. 开发常用的 Android 函数库

    第三方函数库(译者注:包括第三方提供的 SDK,开源函数库)以惊人的方式助力着 Android 开发,借助这些其他开发人员辛勤工作的成果,我们开发起来更轻松和快捷.目前存在成千上万的函数库,如何选择正 ...

  2. Tomcat相关面试题,看这篇就够了!保证能让面试官颤抖!

    Tomcat相关的面试题出场的几率并不高,正式因为如此,很多人忽略了对Tomcat相关技能的掌握. 这次整理了Tomcat相关的系统架构,介绍了Server.Service.Connector.Con ...

  3. nginx 关于client_max_body_size client_body_buffer_size配置

    最近生产环境在这两个参数之间遇到过几次坑.这里记录下.client_max_body_sizeclient_max_body_size 默认 1M,表示 客户端请求服务器最大允许大小,在“Conten ...

  4. selenium下拉到页面最底端

    selenium操控浏览器下拉到页面最底端: #!/usr/bin/env python # -*- coding: utf-8 -*- from selenium import webdriver ...

  5. JVM基础系列第13讲:JVM参数之追踪类信息

    我们都知道 JVM 在启动的时候会去加载类信息,那么我们怎么得知他加载了哪些类,又卸载了哪些类呢?我们这一节就来介绍四个 JVM 参数,使用它们我们就可以清晰地知道 JVM 的类加载信息. 为了方便演 ...

  6. macOS的OpenCL高性能计算

    随着深度学习.区块链的发展,人类对计算量的需求越来越高,在传统的计算模式下,压榨GPU的计算能力一直是重点. NV系列的显卡在这方面走的比较快,CUDA框架已经普及到了高性能计算的各个方面,比如Goo ...

  7. 最快的进程间通信方式你get了么

    前言:天下武功为快不破!在信息爆炸.快速发展的新时代...,扯远了....进程间通信方式有很多,但最快的方式你知道么?由我娓娓道来... 一.共享内存方式 主角闪亮登场了,噔噔瞪...,最快的方式就是 ...

  8. HashMapd的存取原理你知道多少

    在java的容器集合中,hashmap的使用频率可以说是相当高的.不过对于hashmap的存(put())以及取(get())的原理可能很多人还不大清楚,今天,我就给大家介绍下它是如何存如何取的. # ...

  9. MVC实现多级联动

    前言 多级联动(省级联动)的效果,网上现成的都有很多,各种JS实现,Jquery实现等等,今天我们要讲的是在MVC里面,如何更方便.更轻量的实现省级联动呢? 实现效果如下: 具体实现 如图所示,在HT ...

  10. ASP.NET Core 2.0 : 八.图说管道,唐僧扫塔的故事

    本文通过一张GIF动图来继续聊一下ASP.NET Core的请求处理管道,从管道的配置.构建以及请求处理流程等方面做一下详细的研究.(ASP.NET Core系列目录) 一.概述 上文说到,请求是经过 ...