我的网页中嵌入了一个 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: "Open Sans", 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/