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)
View Code

 

元素是否可见的方法

  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形式返回存在的元素

 

原文地址:https://www.cnblogs.com/tynam/p/10343145.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


转载地址:https://www.cnblogs.com/mini-monkey/p/12104821.html前言有时候测试过程中会遇到日期控件场景,这时候需要特殊处理,下文以12306网站为例1.处理方式通常是通过js去除只读属性(2种方法),然后通过send_keys重新写值fromtimeimportsleepdriver=webdriver.Chrome()dr
web自动化测试过程中页面截图相对比较简单,可以直接使用selenium自带的方法save_screenshot()。示例:对百度首页整个页面进行截图。#coding=utf-8fromseleniumimportwebdriverd=webdriver.Chrome()d.get('https://www.baidu.com/')#对页面进行截图d.save_screensh
目录前言一、Selenium简介二、浏览器驱动1.浏览器驱动参考2.Windows下载Chrome驱动三、代码实现1.新建控制台项目WeatherWebCrawler2.选择.NET6.03.安装NuGet包4.将下载好的驱动放到项目生成目录下5.编写代码四、完整代码总结前言提示:爬虫本身并不违法,所有爬虫都
一、iframe的含义:iframe是HTML中框架的一种形式,在对界面添加嵌套另一个页面时可以使用iframe。做ui自动化的时候,元素定位不到的一个很重要原因就是页面存在iframe。Iframe可以比喻成一道门,打开这道门才能进入屋子里。二、怎么判断页面上存在iframe?谷歌浏览器F12(或者右
转载请注明出处❤️作者:测试蔡坨坨原文链接:caituotuo.top/d59b986c.html你好,我是测试蔡坨坨。众所周知,Selenium在2021年10月13号发布了Selenium4,目前最新的版本应该是Selenium4.4.0。以前一直用的Selenium3,那么Selenium4相对Selenium3对我们做自动化测试来说有哪些需要注意的
'''##**认识selenium**​**下载:pipinstallselenium**​官方文档:https://selenium-python.readthedocs.io/###什么是selenium?​selenium是一套完整的web应用程序测试系统,包含了测试的录制(seleniumIDE),编写及运行(SeleniumRemoteControl)和测试的并行处理(SeleniumGr
importtimefromselenium.webdriver.support.waitimportWebDriverWaitfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydriver=webdriver.Chrome(r"D:\百分浏览器\CentBrowser\Application\chromedriver.exe");driver.get("htt
前言:当鼠标悬停在隐藏文本内容上时,显示所有内容。场景案例:百度首页,要选择‘高级搜索’,先得把鼠标放在‘设置上’F12-在页面中搜索‘高级搜索’,找到‘高级搜索’文本,鼠标放到‘设置’上,display的值变为block;鼠标不放上去之前是none,即不可见元素。隐藏的元素操作,会出现报
selenium中的ActionChains初始化时传入driverActionChains中存储的所有行为click(on_element=None)——单击鼠标左键click_and_hold(on_element=None)——点击鼠标左键,不松开context_click(on_element=None)——点击鼠标右键double_click(on_element=None)——双击鼠标
介绍常见的表单元素 Input,button,checkbox,select。表单使用表单标签(<form>)定义。例如:<form><input/></form> 保存HTML到本地进行操作<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title&g
1、处理定位报错的问题判断该元素存在,再输入。判断该元素不存在,抛出异常。依然是通过EC这个模块。2、判断是否存在邮箱地址,存在,再操作。就不用担心元素不存在,程序报错。3、判断传入的元素是否可见,是否在显示范围内。还是要先找元素但这样找,只能顺利的执行一次。fr
1、使用国内的镜像地址https:/egistry.npmmirror.com/binary.html?path=chromedriver/ 2、通过simulation模拟用户点击来下载(只贴出部分方法)#!/usr/bin/envpython#-*-coding:utf-8-*-importosimportplatformimportsignalimporttimeimportallureimport
案例描述https://www.healthsmart.com.hk/hs-home/#!/link/home这个网页你手工打开的时候你会发现一直处于加载中,一定时间后才好。我们的需求是点击会员,弹出菜单,进行下一步操作,如果没有加载好是点不了的(业务特点)。我们来看看代码怎么写示例代码1:时间去哪里了fromselen
  分析了好几个小时淘宝的登陆,对其反爬虫方案有了点思路,先记录一下,后面会持续进行分析。当然想要玩更高级的Python爬虫首先你要把基础打牢,这里小编准备了一份Python爬虫入门资料,进群:700341555即可免费领取!  众所周知目前使用selenium打开浏览器访问淘宝,不管你是手动
在python+selenium中经常会遇到找到的元素不唯一,导致定位到的元素不是预期的或者定位不到元素解决方法:只要在页面进行确认找到的元素唯一后,再进行操作 页面确认方法:1、通过html中检索功能确认进入开发者模式:点击右上角三个点-->选则search进行查找或
引入       使用Scrapy框架爬取某些网站的数据时,往往会页面动态加载数据的情况。如果是直接使用Scrapy对其url发起请求,是绝对获取不到动态加载的数据的。但是通过观察我们会发现,通过浏览器对其url发起请求则会加载出对应的动态数据。那么,如果我们想要在Scrapy中获取
孤荷凌寒自学python第八十五天配置selenium并进行模拟浏览器操作1 (完整学习过程屏幕记录视频地址在文末) 要模拟进行浏览器操作,只用requests是不行的,因此今天了解到有专门的解决方案:selenium模块及与火狐浏览器的配合使用。一、环境配置(一)、安装selenium模块pipinstallse
selenium确认进入了预期页面在自动化操作中,浏览器每次进入一个新的需要,都需要确认该页面是否打开或打开的页面是否是预期的页面需要进行确认页面后方可进行下一步操作确认页面有很多中方法,像笔者所在项目的中每个页面都有一个固定属性(ng-page=‘xxx’)来确认,所以确认页面的时候