You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Python如何定位并切换到嵌套在iframe内部的第二层iframe

Selenium 嵌套 iframe 切换解决方法

嵌套iframe的切换遵循从外到内逐层切入的规则,你已经完成了第一层iframe的切换,接下来只需要在第一层iframe的上下文内定位第二层iframe元素,再执行一次切换操作即可。

具体修改后的代码如下:

import unittest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from .functional_test import FunctionalTest


class MyTest(FunctionalTest):
    URL = '/datastory/my-datastory/'


    @classmethod
    def setUpClass(cls):
        """Set up method."""
        super().setUpClass()

        cls.URL = cls.format_url(cls.URL)
        cls.login_user(cls)

    def test_iframe(self):
        container = self.browser.find_element_by_id('visual-31')
        carousel = container.find_element_by_css_selector('.col-sm-12:nth-child(2) div.visual #classics-50-carousel')
        wait = WebDriverWait(self.browser, 60)
        wait.until(ec.visibility_of(carousel))
        page_source = carousel.get_attribute("src");
        self.assertEqual(
            page_source,
            'https://observablehq.com/embed/@ddsg/paramount-databyte-visuals?cells=classics50yrs'
        )
        # 切换到第一层iframe
        self.browser.switch_to.frame(carousel)
        # 定位第一层iframe内嵌套的第二层iframe,替换下方选择器为你实际第二层iframe的定位规则
        # 支持id、name、xpath、css选择器等任意Selenium定位方式
        second_iframe = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, '替换为第二层iframe的css选择器')))
        # 切换到第二层iframe
        self.browser.switch_to.frame(second_iframe)
        
        # 此处可编写第二层iframe内的操作逻辑
        
        # 切回逻辑:仅需退回上一层(第一层iframe)时使用下面的代码
        # self.browser.switch_to.parent_frame()
        # 需直接切回最外层主页面时使用下面的代码
        self.browser.switch_to.default_content()

注意事项

  • 定位第二层iframe时,必须在切入第一层iframe之后执行定位操作,不能在主页面上下文直接定位内层iframe,否则会抛出元素不存在的异常。
  • 建议对第二层iframe添加显式等待,避免因为第一层iframe加载未完成,导致内层元素还没渲染就执行定位操作。
  • 如果操作完内层iframe后还要操作第一层iframe的内容,优先使用switch_to.parent_frame()退回上一层,不用从最外层重新逐层切入,可提升执行效率。

内容的提问来源于stack exchange,提问作者NewToJS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:54:02