如何使用Selenium WebDriver访问动态添加的iframe?

Bel*_*rog 5 javascript python iframe selenium webdriver

我有一个没有iframe的页面,然后通过JavaScript在点击一个锚点后添加一个iframe.

我遇到的问题是,当我切换到框架时,driver.switch_to_frame(x)我仍然可以找到我的任何内容.

我已经尝试在找到的帧中循环driver.find_elements_by_tag_name('iframe')并检查它们中的每一个我期望找到的类,但没有这样的运气.

driver.switch_to_active_element() 并没有给我正确的iframe.

我不确定iframe内容是否只是无法访问,因为JS DOM更改未反映在Selenium从驱动程序中看到的内容中.我已经为其他iframe完成了同样的过程而没有任何问题,但是这个只是不合作.以下是我正在处理的简化版本.

在JS之前:

<html>
    <body>
      <a onclick="jsmagic">load iframe</a>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

JS之后:

<html>
    <body>
      <iframe><div class='modal'>Message</div></iframe>
      <a onclick="jsmagic">load iframe</a>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Python WebDriver尝试:

driver.switch_to_frame(0)
driver.find_elements_by_class_name('modal')
driver.switch_to_default_content()
Run Code Online (Sandbox Code Playgroud)

我也尝试了类似的变体:

frame = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(frame)
driver.find_elements_by_class_name('modal')
Run Code Online (Sandbox Code Playgroud)

我尝试使用driver.execute_script该事件来访问该对象,但获取内容超出了我的范围.Firefox控制台命令无法通过Selenium运行.

Bel*_*rog 3

看来这是一个时间问题,我最终得到了这样的结果:

def modal_must_show(self, string):
  for _ in range(12):
    for frame in self.driver.find_elements_by_tag_name('iframe'):
      try:
        if not frame.is_displayed():
          continue
        if frame.parent.page_source.find(string):
          return
      except:
        pass
  assert False, 'Modal missing string'
Run Code Online (Sandbox Code Playgroud)