很多 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. [Swift]LeetCode565. 数组嵌套 | Array Nesting

    A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest ...

  2. [Swift]LeetCode824. 山羊拉丁文 | Goat Latin

    A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and up ...

  3. nvidia-docker+cuda8.0+ubuntu16.04

    nvidia-docker安装 如果之前安装过docker1.0版本,需要先删掉该版本和之前创建的容器 docker volume ls -q -f driver=nvidia-docker | xa ...

  4. iReport 5.6.0 Error: net.sf.jasperreports.engine.JRException: Error executing SQL statement for : data 最优解决方案

    问题描述 近期学习iReport(个人使用的是最新版本的 iReport-5.6.0,MySQL是 5.5.56版本),遇到一些问题,在安装完成后,创建了数据库,配置了MySQL数据库连接信息,新建报 ...

  5. 【java爬虫】---爬虫+jsoup轻松爬博客

    爬虫+jsoup轻松爬博客 最近的开发任务主要是爬虫爬新闻信息,这里主要用到技术就是jsoup,jsoup 是一款 Java的HTML解析器,可直接解析某个URL地址.HTML文本内容.它提供了一套非 ...

  6. SpringBoot+MyBatis+MySQL读写分离

    1.  引言 读写分离要做的事情就是对于一条SQL该选择哪个数据库去执行,至于谁来做选择数据库这件事儿,无非两个,要么中间件帮我们做,要么程序自己做.因此,一般来讲,读写分离有两种实现方式.第一种是依 ...

  7. windows部署MongoDB

    打开MongoDb下载页面,分别下载Community Server和Compass,注意在安装Community Server时可以勾选同时安装Compass,但会比较慢,所以建议两个分开下载安装. ...

  8. leetcode — unique-binary-search-trees

    /** * Source : https://oj.leetcode.com/problems/unique-binary-search-trees/ * * * Given n, how many ...

  9. Docker系列09—Docker的系统资源限制及验证

    本文收录在容器技术学习系列文章总目录 1.限制容器的资源 默认情况下,容器没有资源限制,可以使用主机内核调度程序允许的尽可能多的给定资源.Docker提供了控制容器可以使用多少内存或CPU的方法,设置 ...

  10. SpringCloud-Greenwich版本新特性探索(1)---SpringCloudGateway

    一.前言 1.SpringCloudGateway是SpringCloud新推出的网关框架,比较于上一代Zuul,功能和性能有很大的提升.Zuul1.x采用的是阻塞多线程方式,也就是一个线程处理一个连 ...