【问题标题】:Switching back to parent frame after it's no longer in DOM in Selenium在 Selenium 中不再在 DOM 中后切换回父框架
【发布时间】:2018-07-04 13:51:02
【问题描述】:

我有以下页面

<body>
  <iframe id="outer_frame">
    <iframe id="search_button_frame">
      <button id="search_button"></button>
    </iframe>
  </iframe>
</body>

现在我点击search_button 后,两个frames outer_framesearch_button_frame 不再在DOM 中,而是页面变成了这样

<body>
  <iframe id="form_frame">
    ...
  </iframe>
</body>

我正在尝试转到search_button,然后跳出框架进入主页,然后使用以下命令切换到form_frame

outer_frame = browser.find_element_by_xpath('//*[@id="outer_frame"]')
browser.switch_to.frame(outer_frame)

search_button_frame = browser.find_element_by_xpath('//*[@id="search_button_frame"]')
browser.switch_to.frame(search_button_frame)

search_button = browser.find_element_by_xpath('//*[@id="search_button"]')
search_button.click()

browser.switch_to_default_content()

form_frame = browser.find_element_by_xpath('//*[@id="form_frame"]')
browser.switch_to.frame(form_frame)

但我不断收到以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Una
ble to locate element: {"method":"xpath","selector":"//*[@id="form_frame"]"}

这是否意味着我没有定位在正确的框架中?

【问题讨论】:

  • IMO,你做得很好。在切换到 form_frame 之前添加一些等待,并将所有 xpath 替换为 id。

标签: python selenium selenium-webdriver iframe webdriver


【解决方案1】:

根据您的问题和点击search_buttonDOM Tree 结构后,您需要先切换default_content(),然后使用 切换到下一个所需的&lt;iframe&gt; >WebDriverWait如下:

driver.switch_to.default_content()
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"form_frame")))

您可以在以下位置找到详细讨论:

【讨论】:

  • 谢谢!有效!但是我认为它应该是WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"form_frame"))),因为只使用一个括号会产生以下错误 TypeError: __init__() takes exactly 2 arguments (3 given)
【解决方案2】:

按照标准程序:首先,保存浏览器的父句柄。 字符串句柄 = driver.getwindowhandle();

然后尝试切换到带有等待的帧,以便驱动程序可以等待一段时间,如果它现在不存在于 DOM 中。 完成框架上的工作后,再次切换到 parentWindow(默认窗口)。 相同的过程可以应用于始终完美运行的每一帧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多