javascript - 单击 iframe 中的元素 - Selenium Python

标签 javascript python html selenium iframe

我的网页中嵌入了一个 iframe,并且我正在使用 Selenium 来自动化测试:

<iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="display: block; background-color: rgb(255, 255, 255); border-collapse: separate; border-color: rgb(163, 192, 216); border-style: solid; border-width: 1px; clear: none; float: none; margin: 0px; outline: rgb(0, 0, 0) none 0px; outline-offset: 0px; padding: 6px 12px; position: static; top: auto; left: auto; right: auto; bottom: auto; z-index: auto; vertical-align: baseline; text-align: start; box-shadow: rgba(0, 0, 0, 0.043) 0px 0.595067px 0.595067px 0px inset; border-radius: 4px; width: 100%; height: 434px;"></iframe>

iframe 内有一个正文:

<body marginwidth="0" marginheight="0" contenteditable="true" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty wysihtml5-editor placeholder" spellcheck="true" style="background-color: rgb(255, 255, 255); color: black; cursor: text; font-family: &quot;Open Sans&quot;, sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: 400; line-height: 17.1429px; letter-spacing: normal; text-align: start; text-decoration: none solid rgb(0, 0, 0); text-indent: 0px; text-rendering: auto; word-break: normal; overflow-wrap: break-word; word-spacing: 0px;">Enter text ...</body>

我编写了以下 Selenium 自动化来将文本输入到该正文中,该正文实际上显示为文本框:

iframes = wait.until(EC.frame_to_be_available_and_switch_to_it((By.CLASS_NAME, "wysihtml5-sandbox")))
if iframes:
    try:
        body = browser.find_elements_by_tag_name("body")
        for b in body:
            b.clear()
            b.send_keys(text)
        time.sleep(2)
        # switch back to the original content
        browser.switch_to.default_content()
    except Exception as e:
       print(e)

问题是每当我输入文本(“foobar”)并保存时,文本都不会保存。我注意到,如果我单击正文代表的输入框,则会保存 text ,否则不会发生。我猜想为该页面编写代码的人都希望用户单击并在输入框 (body) 中键入内容,以便在 iframe 关闭时进行保存。 如何模拟单击 iframe 输入框的相同效果,以修复自动化中的此错误?

最佳答案

您可以尝试以下选项。

选项 1: 在输入文本/清理文本之前单击正文元素。

b.click()
# use javascript click(), if normal click not worked
driver.execute_script("arguments[0].click()",b)

选项 2: 在正文中输入数据后,触发 on-change 或关联事件。

driver.execute_script("arguments[0].dispatchEvent(new Event('onchange', {'bubbles': true,'cancelable': true}));",b)

您可以尝试单独或组合使用这两个选项。

引用此post了解与 body 元素关联的事件。

关于javascript - 单击 iframe 中的元素 - Selenium Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60123541/

相关文章:

javascript - 我需要将函数重新制作成一个类

javascript - 我想设置一个倒计时时间并保持截止日期减少 php

javascript - 环境变量更改project.json中的应用程序名称并设置运行时变量?

python - 如何删除列表中的重复数字,然后替换为新的随机数

python - 从扭曲的服务器向特定客户端发送数据

javascript - 如何在 Jasmine 测试框架中处理谷歌地图事件

javascript - 难道Python运行时模型是字典的字典吗?

html - iOS 应用程序中 HTML 文件中的图片

html - 我如何在 Ipad 上将图像居中

javascript - 当使用 jqueryeach 将 tr 附加到表 thead 时,结果是空白行