【问题标题】:Selenium with Python: Send keys to an iframeSelenium 与 Python:将密钥发送到 iframe
【发布时间】:2017-06-18 17:40:53
【问题描述】:

我浏览了一些关于 SO 的帖子,并使用了建议的切换到 iframe 的方法 -

driver.switch_to.frame(driver.find_element_by_id(iFrameID))
element = driver.find_element_by_xpath('HTML/BODY')

但是,我得到一个 NoSuchElementException 用于 xpath 的查找。

然后我在切换到iframe后添加了print (driver.page_source),看到了如下结构-

<HTML dir=ltr><HEAD><LINK rel=stylesheet type=text/css 
href="/_layouts/1033/styles/core.css">
<META name=GENERATOR content="MSHTML 11.00.9600.18639"></HEAD>
<BODY class=ms-formbody contentEditable=true style="BORDER-TOP: medium none; 
BORDER-RIGHT: medium none; BORDER-BOTTOM: medium none; BORDER-LEFT: medium 
none; BACKGROUND-COLOR: white" scroll=yes WebLocale="1033"
BaseElementID="baseTextField" wordWrap="false" RestrictedMode="true">
<DIV></DIV></BODY></HTML>

HTML/BODY 结构肯定存在,所以我不确定我在 find_element_by_xpath 中做错了什么。我还尝试了 /HTML/BODY 和//HTML/BODY,但没有成功。

作为一种解决方法,我尝试通过单击 iframe 然后使用 ActionChains 使 RTE 成为焦点

driver.find_element_by_id(iFrameID).click()
actions = ActionChains(driver)
actions.send_keys("Lorem Ipsum")
actions.perform()

但出现以下错误:

NameError: name ActionChains is not defined

任何帮助将不胜感激

【问题讨论】:

  • 如果您可以发布您的源代码,我可能会提供帮助:)
  • 很明显你缺少导入,试试from selenium.webdriver import ActionChains
  • 你真的可以复制粘贴你试图切换到的&lt;iframe&gt;标签的HTML吗? driver.page_source 的输出已被截断。停止依赖这种方法......它是不一致的,并且不会做你认为它做的事情。 @AzatIbrakov 他正在尝试切换到iframe,正如您所指出的,他首先遇到了库导入。但是,对于driver.find_element_by_id(iFrameID).click() 命令,他仍然会收到NoSuchElementException 错误。
  • @Sid 您能否考虑更新您尝试切换的 iframe 的 HTML DOM?切换到 iframe 后,请更新下一步。谢谢
  • @Sid,你为什么要点击iframe 并发送文本到ActionChains() 实例!?分享你到底想做什么,因为现在你的逻辑还不清楚

标签: python selenium iframe selenium-webdriver


【解决方案1】:

这篇文章有点老了,但我希望我的解决方案能够帮助那些面临类似问题的人。

所以我设法使用 Selenium Python 将密钥发送到 IFrame 的方式是在切换到 iframe 后首先使用 iframe 的 switch_to_frame,我们可以使用 driver.find_element 像新文档一样查询文档

示例如下所示

#Select iFrame
element = driver.find_element_by_id(iFrameID)

#Switch to iFrame
driver.switch_to_frame(element)

#Query document for the ID that you're looking for
queryElement = driver.find_element_by_id(queryID)

#Send key to the ID
queryElement.send_keys("L")

#Switch back to default content from iFrame
driver.switch_to_default_content()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多