Of course. The URL https://selectorshub.com/iframe-scenario/ is a great page for practice because it is specifically designed to demonstrate challenges like iframes, nested iframes, and Shadow DOM.
Because of these complexities, you can't simply get one list of XPaths. You have to consider the context (which frame you are in). A standard XPath will only work on the main page content.
Here is a breakdown of the key elements and their XPaths, organized by their location on the page.
1. Elements in the Main Document (Top Level)
These XPaths work directly without needing to switch into any iframes.
2. Elements inside the First Iframe (id="pactothefuture")
To access these elements, you must first switch your automation tool's context to this iframe.
Example in Selenium (Python):
driver.switch_to.frame("pactothefuture")
Once inside this frame, the following XPaths will work:
3. Elements inside the Shadow DOM (within the first iframe)
The "Your Name" input field is special. It's inside a Shadow DOM, which is nested inside the first iframe.
Important: Standard XPath cannot penetrate a Shadow DOM. You must use CSS selectors with JavaScript execution in tools like Selenium.
To locate the "Your Name" input field:
- Switch to the first iframe:
driver.switch_to.frame("pactothefuture")
- Access the Shadow DOM host element: This is the element that contains the shadow root. Its ID is
sn_hce.
- Use JavaScript to query inside the Shadow DOM.
Example JavaScript to find the element:
document.querySelector('#sn_hce').shadowRoot.querySelector('#glaf')
There is no direct XPath for this element.
4. Elements inside the Nested Iframe (id="packyak")
This iframe is inside the first iframe. To access its elements, you must perform two switches.
Example in Selenium (Python):
# 1. Switch to the first iframe
driver.switch_to.frame("pactothefuture")
# 2. From within the first iframe, switch to the nested one
driver.switch_to.frame("packyak")
Once inside this nested frame, the following XPaths will work:
How to Switch Back
After you are done working inside an iframe, you need to switch back to the main document to interact with top-level elements again.
Example in Selenium (Python):
driver.switch_to.default_content()
Summary of Concepts
| Element Location | How to Access It | Example XPath / Selector |
|---|
| Main Page | No switch needed. | //input[@id='userPass'] |
| First Iframe | Switch to the iframe first (id="pactothefuture"). | //input[@id='country'] |
| Nested Iframe | Switch to the first iframe, then switch to the nested iframe (id="packyak"). | //input[@id='tea'] |
| Shadow DOM (in 1st iframe) | Switch to the iframe, then use JavaScript to query the Shadow DOM. XPath will not work. | CSS Selector: #sn_hce -> (shadowRoot) -> #glaf |
| Back to Main Page | Switch back to the default content. | driver.switch_to.default_content() |