Python-Selenium 查找不可点击的可点击元素

2024-04-17

我在用python-selenium运行自动化测试。在复杂的非公共环境中运行这些测试时,我发现了一些我将标记为 selenium 中的错误的东西。

基本上我想做的是在 DOM 中找到一些元素,当它变得可点击时,然后点击它。代码如下:

....
what = (By.XPATH, '//button/span[contains(text(), "Load")]')
element = WebDriverWait(bspdriver.webdriver, 60).\
                until(EC.element_to_be_clickable(what))
element.click()
....

但是,那click方法几乎立即失败,并显示以下错误消息:

ElementClickInterceptedException: Message: Element <button class="ivu-btn ivu-btn-primary ivu-btn-long ivu-btn-small" type="button"> is not clickable at point (1193.3332901000977,522) because another element <div class="ivu-modal-wrap vertical-center-modal circuit-loading-modal"> obscures it

我虽然我正在等待元素可点击的!我假设EC.element_to_be_clickable正是这个意思。但事实并非如此。这是硒中的错误吗?

解决方法是使用以下代码:

    mustend = time.time() + 60
    while time.time() < mustend:
        try:
            WebDriverWait(bspdriver.webdriver, 60).\
                until(EC.element_to_be_clickable(what)).click()
            break
        except (TimeoutException, NoSuchElementException,
                StaleElementReferenceException,
                ElementClickInterceptedException) as e:
            time.sleep(1.0)

这对我来说看起来不太好。有没有办法改进代码?硒有缺陷吗?如果是的话我可以举报...

使用过的包:

  • 硒 3.8.0 和 3.11.0
  • 壁虎驱动程序 0.19.1
  • 蟒蛇2.7.12
  • py.测试3.6.1

完整错误消息:

....
>       element.click()
selenium/test_pair_recording.py:66: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../venvs/linux_selenium/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py:80: in click
    self._execute(Command.CLICK_ELEMENT)
../venvs/linux_selenium/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py:501: in _execute
    return self._parent.execute(command, params)
../venvs/linux_selenium/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py:311: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x7fe69694fd90>
response = {'status': 400, 'value': '{"value":{"error":"element click intercepted","message":"Element <button class=\"ivu-btn ivu...gate@chrome://marionette/content/listener.js:414:13\nclickElement@chrome://marionette/content/listener.js:1220:5\n"}}'}

    def check_response(self, response):
        """
            Checks that a JSON response from the WebDriver does not have an error.

            :Args:
             - response - The JSON response from the WebDriver server as a dictionary
               object.

            :Raises: If the response contains an error message.
            """
        status = response.get('status', None)
        if status is None or status == ErrorCode.SUCCESS:
            return
        value = None
        message = response.get("message", "")
        screen = response.get("screen", "")
        stacktrace = None
        if isinstance(status, int):
            value_json = response.get('value', None)
            if value_json and isinstance(value_json, basestring):
                import json
                try:
                    value = json.loads(value_json)
                    if len(value.keys()) == 1:
                        value = value['value']
                    status = value.get('error', None)
                    if status is None:
                        status = value["status"]
                        message = value["value"]
                        if not isinstance(message, basestring):
                            value = message
                            message = message.get('message')
                    else:
                        message = value.get('message', None)
                except ValueError:
                    pass

        exception_class = ErrorInResponseException
        if status in ErrorCode.NO_SUCH_ELEMENT:
            exception_class = NoSuchElementException
        elif status in ErrorCode.NO_SUCH_FRAME:
            exception_class = NoSuchFrameException
        elif status in ErrorCode.NO_SUCH_WINDOW:
            exception_class = NoSuchWindowException
        elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
            exception_class = StaleElementReferenceException
        elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
            exception_class = ElementNotVisibleException
        elif status in ErrorCode.INVALID_ELEMENT_STATE:
            exception_class = InvalidElementStateException
        elif status in ErrorCode.INVALID_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR \
                or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
            exception_class = InvalidSelectorException
        elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
            exception_class = ElementNotSelectableException
        elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
            exception_class = ElementNotInteractableException
        elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
            exception_class = InvalidCookieDomainException
        elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
            exception_class = UnableToSetCookieException
        elif status in ErrorCode.TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.SCRIPT_TIMEOUT:
            exception_class = TimeoutException
        elif status in ErrorCode.UNKNOWN_ERROR:
            exception_class = WebDriverException
        elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
            exception_class = UnexpectedAlertPresentException
        elif status in ErrorCode.NO_ALERT_OPEN:
            exception_class = NoAlertPresentException
        elif status in ErrorCode.IME_NOT_AVAILABLE:
            exception_class = ImeNotAvailableException
        elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
            exception_class = ImeActivationFailedException
        elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
            exception_class = MoveTargetOutOfBoundsException
        elif status in ErrorCode.JAVASCRIPT_ERROR:
            exception_class = JavascriptException
        elif status in ErrorCode.SESSION_NOT_CREATED:
            exception_class = SessionNotCreatedException
        elif status in ErrorCode.INVALID_ARGUMENT:
            exception_class = InvalidArgumentException
        elif status in ErrorCode.NO_SUCH_COOKIE:
            exception_class = NoSuchCookieException
        elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
            exception_class = ScreenshotException
        elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
            exception_class = ElementClickInterceptedException
        elif status in ErrorCode.INSECURE_CERTIFICATE:
            exception_class = InsecureCertificateException
        elif status in ErrorCode.INVALID_COORDINATES:
            exception_class = InvalidCoordinatesException
        elif status in ErrorCode.INVALID_SESSION_ID:
            exception_class = InvalidSessionIdException
        elif status in ErrorCode.UNKNOWN_METHOD:
            exception_class = UnknownMethodException
        else:
            exception_class = WebDriverException
        if value == '' or value is None:
            value = response['value']
        if isinstance(value, basestring):
            if exception_class == ErrorInResponseException:
                raise exception_class(response, value)
            raise exception_class(value)
        if message == "" and 'message' in value:
            message = value['message']

        screen = None
        if 'screen' in value:
            screen = value['screen']

        stacktrace = None
        if 'stackTrace' in value and value['stackTrace']:
            stacktrace = []
            try:
                for frame in value['stackTrace']:
                    line = self._value_or_default(frame, 'lineNumber', '')
                    file = self._value_or_default(frame, 'fileName', '<anonymous>')
                    if line:
                        file = "%s:%s" % (file, line)
                    meth = self._value_or_default(frame, 'methodName', '<anonymous>')
                    if 'className' in frame:
                        meth = "%s.%s" % (frame['className'], meth)
                    msg = "    at %s (%s)"
                    msg = msg % (meth, file)
                    stacktrace.append(msg)
            except TypeError:
                pass
        if exception_class == ErrorInResponseException:
            raise exception_class(response, message)
        elif exception_class == UnexpectedAlertPresentException and 'alert' in value:
            raise exception_class(message, screen, stacktrace, value['alert'].get('text'))
>       raise exception_class(message, screen, stacktrace)
E       ElementClickInterceptedException: Message: Element <button class="ivu-btn ivu-btn-primary ivu-btn-long ivu-btn-small" type="button"> is not clickable at point (1193.3332901000977,522) because another element <div class="ivu-modal-wrap vertical-center-modal circuit-loading-modal"> obscures it

../venvs/linux_selenium/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py:237: ElementClickInterceptedException

失败的原因是因为ElementToBeClickable正在等待元素被启用,它并不是真正检查该元素是否可点击,而是假设如果元素已启用,则该元素是可点击的,实际上这是真的,但这里失败了,因为即使另一个元素覆盖所需元素,该元素也会被启用。

所以写这段代码让覆盖层消失

WebDriverWait(bspdriver.webdriver,10).until(EC.invisibility_of_element_located((By.XPATH, "//div[@class='ivu-modal-wrap vertical-center-modal circuit-loading-modal']")));

然后你写你的代码

what = (By.XPATH, '//button/span[contains(text(), "Load")]')
element = WebDriverWait(bspdriver.webdriver, 60).\
                until(EC.element_to_be_clickable(what))
element.click()

如果覆盖是临时的,则上述解决方案将起作用,如果它是永久的,则执行 Javascript 单击,因为 WebDriver 内部检查会阻止您执行单击。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python-Selenium 查找不可点击的可点击元素 的相关文章

  • 更改 django 应用程序名称时迁移历史记录不一致

    我正在尝试重命名 django 网站中的应用程序之一 还有另一个应用程序依赖于它及其 mysql 表 我检查了两个应用程序中的所有文件 并将旧名称的实例更改为新名称 但是 现在我在尝试执行迁移时遇到此错误消息 File Users Limo
  • 从另一个文件导入函数,在哪里导入其他库?

    很简单的问题 我搜了一下没有结果 假设我有一个文件 funcs py 其中有一个我想调用当前脚本的函数 该函数使用另一个库 例如 pandas 我在哪里导入该库 约定是什么 我是否将它放在 funcs py 的函数内 funcs py de
  • ./manage.py 使用 https 运行服务器

    manage py 运行服务器 0 0 0 0 8000 我使用上面的行作为我从 github 借用的代码的一部分 https github com ribeiroit boh puppet https github com ribeiro
  • 图像从部署到heroku的django web应用程序中消失

    我正在开发一个 django 项目 使用 django Rest 框架编写 REST API 以在 Android 应用程序中使用它们 我的主要想法是在 Django 中开发后端 在 Android 中开发前端 项目部署在 Heroku 上
  • 如何有效地将多个 pandas 列组合成一个类似数组的列?

    使用对象类型列之类的东西创建 或加载 DataFrame 很容易 如下所示 In pdf pd DataFrame a 1 2 3 b 4 5 6 c 7 8 9 combined 1 4 7 2 5 8 3 6 9 Out a b c c
  • selenium.common.exceptions.SessionNotCreatedException:消息:未从选项卡创建的会话使用 ChromeDriver Chrome Selenium Python 崩溃

    当我尝试访问脚本请求的没有特定的 url 时 显然出现此错误 我不明白为什么会出现这个错误 但我想对其进行处理 以免在发生错误时中止脚本 这会重复 但不能解决我的问题 如何避免错误 selenium common exceptions Se
  • ConfigParser 从 INI 文件中获取值,如下所示

    我有以下类型的 INI 文件 section1 subsection1 port 989 section1 subsection2 somethign somethign 我正在使用 Python 的 ConfigParser 来解析 IN
  • 在嵌套有序字典 python 中查找给定键的值

    我试图从嵌套的 OrderedDict 中查找给定键的值 关键点 我不知道这个字典会嵌套多深 我正在寻找的键的名称是不变的 它将位于字典中的某个位置 我想返回本例中名为 powerpoint color 的键的值 mydict Ordere
  • 继续在文件的同一行写入

    我已经使用以下命令打开了要写入的文件 data open input a 使用循环 我想在同一行中向文件写入一些单词 在每次循环迭代之后我想添加一个换行符 while loop for loop do something if some c
  • 如何在屏幕上锚定 Tkinter 窗口(不可移动窗口)

    我正在尝试在特定位置打开 tkinter 如果它是不可移动的 那就更好了 我搜索文档和其他内容 但没有找到任何相关内容 最好的方法是将顶部或底部固定在一个位置 x y 如果需要 我可以调整窗口大小 def my functions prin
  • Python:将字典转换为字节

    我正在尝试将字典转换为字节 但在将其转换为正确的格式时遇到问题 首先 我尝试使用自定义架构映射字典 模式定义如下 class User def init self name None code None self name name sel
  • Tensorflow:使用 Adam 优化器

    我正在张量流中试验一些简单的模型 包括一个看起来与第一个非常相似的模型面向 ML 初学者的 MNIST 示例 http www tensorflow org tutorials mnist beginners index md 但维数稍大一
  • 将 pdf 图像转换为 jpg 图像的最快方法是什么? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我正在尝试将多个 pdf 10k 转换为 jpg 图像并从中提取文本 我目前正在使用pdf2imagepython 库 但它相当慢 有没有比这更
  • python 解码部分 utf-8 字节数组

    我从不了解 UTF 8 规则的通道获取数据 因此 有时当 UTF 8 使用多个字节来编码一个字符并且我尝试将部分接收到的数据转换为文本时 我在转换过程中遇到错误 根据接口的性质 没有任何结束的流 我无法找出数据何时已满 因此我需要处理部分
  • 绘制顶部有函数线的直方图

    我正在尝试使用 SciPy 进行统计 使用 matplotlib 进行绘图 在 Python 中进行一些分布绘图和拟合 我在创建直方图等方面运气很好 seed 2 alpha 5 loc 100 beta 22 data ss gamma
  • 请求库在 HTTPS 代理 CONNECT 上强制使用 HTTP/1.1

    我遇到了 HTTP 代理服务器行为异常的问题 不幸的是 我无法控制代理服务器 它是 IBM 的 企业 产品 代理服务器是用于软件测试的服务虚拟化解决方案的一部分 根本问题 我认为 是代理服务器发回 HTTP 1 0 响应 我可以从 SOAP
  • python matplotlib 无边框表格

    我在表格顶部有一个由以下示例生成的图 表格数据被随机数替换 实际绘图被一些任意函数替换 import numpy as np import matplotlib pylab as plt fig ax plt subplots ntp 17
  • 添加类方法后如何更新类的实例?

    我发现自己陷入了困境 我开发了一个类 然后创建了该类的一个实例 这些类通常会执行数据和统计操作 这些操作需要很长时间 有时需要 20 分钟 我将继续开发我的类 并向其中添加其他方法 现在 如何使用新方法更新以前的类实例而不重新初始化该类的旧
  • 如何捕获密码提示

    我有以下代码 更新为包括 pexpect import sys import subprocess import pexpect print 0 ssh subprocess Popen ssh A t email protected cd
  • 从基类调用重写的方法?

    深入Python http diveintopython net object oriented framework userdict html Python 的原作者 Guido 是这样解释方法重写的 派生类可以重写其基类的方法 因为方法

随机推荐

  • 项目“ ”的目标位置已存在,无法移动项目

    当我尝试与 git 存储库共享我的项目时 出现这样的异常 项目的目标位置 已存在 无法移动项目 写一个答案是因为我尝试了许多类似问题中建议的许多选项 但没有一个起作用 然后我按照以下有效步骤手动完成了此操作 并且这些步骤适用于任何 Ecli
  • 使用正则表达式查找有效的 IP 地址

    我有以下字符串 text 10 0 0 1 1 but 127 0 0 256 1 1 1 1 我想返回有效的IP地址 所以它应该只返回1 1 1 1自从这里256高于255并且第一个IP编号过多 到目前为止 我有以下内容 但它不适用于0
  • 抽象与抽象类

    根据http www cs cornell edu courses cs211 2006sp Lectures L08 abstraction 08 abstraction html http www cs cornell edu cour
  • 为什么 TableAttribute 位于实体框架 Dll 中?

    Table 属性 可用于将 POCO 类映射到正确的数据库名称 架构 位于 EntityFramework dll 中是否有充分的理由 这是否会阻止您创建一个仅包含您的实体而不依赖于特定数据访问技术的域项目 例如 如果我使用此属性 我不相信
  • CLGeocoder 返回其他国家/地区的位置

    我有以下代码 CLGeocoder geo CLGeocoder alloc init CLRegion region CLRegion alloc initCircularRegionWithCenter CLLocationCoordi
  • 在Sandbox中使用Cocoa NSSavePanel导致断言失败

    我正在尝试使用 NSSavePanel 并将这一行添加到我的代码中 let test NSSavePanel 每次调用此代码时都会出现此错误 我不太确定这里发生了什么 因为我只是创建一个新对象 任何帮助表示赞赏 谢谢 Assertion f
  • 如何在 MVC Core 和 AutoFac 中使用属性注入

    我可以在 MVC Core 中轻松使用构造函数参数注入 但不支持属性注入 我尝试使用 AutoFac 但也失败了 那么如何在MVC Core中使用属性注入 这是 AutoFac 的代码 services AddMvc ContainerBu
  • 使用 Linkify Android 打开 Activity

    我想在用户使用 linkify 单击 textView 时打开 Activity 这是我的代码 Pattern tagMatcher Pattern Compile A Za z0 9 Scheme for Linkify when a w
  • C++ 中的 malloc/free 和 new/delete 兼容性?

    malloc free 和 new delete 有一个很好的比较here https stackoverflow com questions 240212 what is the difference between new delete
  • 致命错误:netinet/in.h:没有这样的文件或目录

    套接字编程 UDP 服务器 我正在尝试使用 UDP 服务器进行消息加密和解密 代码在这里 https www geeksforgeeks org message encryption decryption using udp server
  • 创建一个 python 脚本来安装 python 模块并运行一些命令

    我想围绕这个库创建一个薄包装https github com jupyter incubator sparkmagic installation https github com jupyter incubator sparkmagic i
  • Django - ImportError:无法导入名称 Celery

    这是我第一次使用 celery 我完成了这个教程 将 celery 与 Django 一起使用 http docs celeryproject org en latest django first steps with django htm
  • 如何解码哈希

    如果攻击者可以访问用户的数据库并且密码存储在哈希值中 攻击者可以解码该哈希值吗 您能推荐任何可以解码哈希值的工具吗 您可以在这里找到更多详细信息 http crackstation net hashing security htm http
  • C#/WPF:如何单独显示 ListView 的最后一行?

    我有一个 ListView 其中包含大约 10 个 GridViewColumn 和大约 100 行 行 我想在 ListView 的底部显示 总计 或摘要行 有谁知道如何做到这一点 保持 ColumnWidth 等像其他一样并将其作为一个
  • 在 UITextview 中加载巨大的文本文件会崩溃

    我想更新 UITextView 中的一个巨大的文本文件 但设备有时会挂起或崩溃 文本文件大小为 4MB UITextView 是从 Interface Builder 添加的 我正在从文档目录加载文件 以下是加载文本文件的代码 NSErro
  • 如何从函数返回值 - React Native

    如何从反应本机函数返回布尔值 它可以这样完成 export function isJson str try JSON parse str catch e return false return true 该函数检查提供的值是否有效JSON
  • 检查标准输入缓冲区是否为空

    我正在尝试用字符读取数字字符 但我不知道标准输入缓冲区是否为空 我的第一个解决方案是寻找 n标准输入缓冲区中的字符 但是如果我要输入由分隔符分隔的多个数字 这就没用了 我如何知道标准输入缓冲区中是否有字符 我需要用 C 语言来完成它并且是可
  • 编译后的第一次执行非常慢,除非“明显”所有循环都会停止

    我这个标题的意思是 在某些情况下 构建整个程序后 它的第一次执行将需要大约 25 秒才能开始 直到第一个 printf 在控制台上显示 接下来的执行几乎立即开始 正如它们应该的那样 添加 删除一个空格并再次编译 之后的第一次执行再次变得极其
  • 如何在同一图上显示条形图和折线图

    我无法在同一绘图上显示条形图和折线图 示例代码 import pandas as pd import numpy as np import matplotlib pyplot as plt Df pd DataFrame data np r
  • Python-Selenium 查找不可点击的可点击元素

    我在用python selenium运行自动化测试 在复杂的非公共环境中运行这些测试时 我发现了一些我将标记为 selenium 中的错误的东西 基本上我想做的是在 DOM 中找到一些元素 当它变得可点击时 然后点击它 代码如下 what