硒 (Python) >> selenium.common.exceptions.NoSuchFrameException:

Selenium (Python) >> selenium.common.exceptions.NoSuchFrameException:

我一直在尝试进入 iframe 并在 Safari 的搜索栏(标记)中写入文本:

我不能 post html,因为它很大而且不是我的,但这是 iframe 代码:

<iframe frameborder="0" id="contentIFrame0" name="contentIFrame0" title="Área de contenido" style="border: 0px none; overflow: hidden; position: absolute; left: 0px; right: 0px; height: 100%; width: 100%; visibility: visible; display: block;"> (...Content of the iframe...) </iframe>

这里是python代码:

wait.until(ec.frame_to_be_available_and_switch_to_it((By.XPATH, '//*[@id="contentIFrame0"]')))
chk_elem = wait.until(ec.visibility_of_element_located((By.XPATH, '//*[@id="2crmGrid_findCriteria"]')))
act = ActionChains(driver)
act.move_to_element(chk_elem)
act.send_keys('Search input', Keys.ENTER).perform()

但我总是得到这个异常:"selenium.common.exceptions.NoSuchFrameException: Message:"。

我看了一些教程,甚至阅读了官方文档,我想我的代码还可以。为什么它不起作用?

PD: 在我 posted 和 XPATH 编写得很好的 iframe 之前没有另一个 iframe。我不知道它是否相关,但我们正在谈论来自 Microsoft 的动态服务网站,以防万一。

这个错误信息...

selenium.common.exceptions.NoSuchFrameException

...表示 driven 实例无法找到 <iframe> 元素。


您采用了正确的方法。理想情况下,找到 you have to induce WebDriverWait inconjunction with expected_conditions set as frame_to_be_available_and_switch_to_it().

但是,出现此错误的原因有很多,其中一些原因和解决方案如下:

  • 所需的 iframe 可能是其父 iframe[=78] 中的嵌套 iframe =].在这些情况下,您必须先诱导 WebDriverWait 切换到 parent iframe,然后再切换到 child iframe如下:

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"parent_iframe_xpath")))
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"child_iframe_xpath")))
    
  • 如果您在两个同级 iframe 之间切换,那么您首先需要先切换回 default_content,然后再切换到同级 iframe如下:

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"sibling_iframe_A")))
    driver.switch_to.default_content()
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"sibling_iframe_B")))
    

You can find a detailed discussion in How to address “WebDriverException: Message: TypeError: can't access dead object” and wait for a frame to be available using Selenium and Python

  • 有时多个 iframe 可以具有相同属性的相似值。在这些情况下,您可能需要构造 ,它使用 src 属性唯一标识 <iframe> 元素,如下所示:

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id="iframe_id and @src='iframe_src'"]")))
    

You can find a detailed discussion in

  • 最后,您需要确保二进制版本兼容,您可以在以下位置找到一些相关讨论:

    • Which Firefox browser versions supported for given Geckodriver version?
    • What is the correct IEDriverServer version to use with IE 11 through Selenium
  • WebDriverWait 配置的 timeout 可能太少,在这种情况下,您需要增加超时时间,因为以下;:

    WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"parent_iframe_xpath")))
    

参考

您可以在以下位置找到一些参考讨论:

  • Switch to an iframe through Selenium and python