Search code examples
pythonselenium-webdriverautomationshadow-dombrowser-automation

Python-Selenium: How to 'switch_to.active_element' to an input element inside a shadow dom?


I am writing a QA automation script using Python and Selenium.

I want to check if the input is already focused when the webpage is rendered. My problem is that I can't find a way to get the currently focused input that is inside the shadow dom.

HTML doc looks like this:

<div>
  #shadow-root
    # this input element is already focused when the page is rendered
    <input type='text'>
</div>

I've tried driver.switch_to.active_element but it always returns None, probably because it can't access shadow dom.

I hope anyone knows another way to get the currently focused input element inside a shadow dom


Solution

  • When the webpage is rendered though you observe that the <input> is already focused but Selenium's focus is at the Top Level Browsing Context.

    So to identify the <input> element you need to bring Selenium's focus within the shadow-root first.

    You can find a relevant detailed discussion in PrintText-How to extract info within a #shadow-root (open) using Selenium Python