How to access shadow dom [Closed] element in selenium?
Recently someone posted a challenge in linked to fill value inside a field. It looks a simple problem as from UI page, it was just a normal input field. I tried to check the dom for the element, and got to know that this is inside closed shadow dom.
So if you also find an element inside shadow dom which is closed, it means it can not be interactable. So the first approach to solve such issue is to connect with your developer teams. Yes, they can provide you an alternate way to access that element (at least in lower environment.)
But if this is not possible, then use selenium keypress method by using a common use case of an end user.
The same way I solved that challenge also. :)
So, Just think, that this field is not accessible from mouse. In this situation, usually we interact on the page items with keyboard "TAB" key. Same approach, we can take here as well.
We just need to find an element which is accessible from selenium usual locator finding techniques, bring focus to that element, sometimes just by clicking on it or if it is an input field, just by passing a empty string, then press tab key until you reach to that element.
Bingo, you are now inside that field, now if you need to perform:
1. Click on that element, press "Enter" key
2. If it is an input field, you can simply use "send_keys" method
To demonstrate it, I created a sample page having shadow root as closed in it.
In the above page, the "Age field " is not inside any shadow dom element. And the first name and last name fields are inside the shadow dom[closed].
So to enter value inside the firstname field, I entered value or bring my focus to "Age field " first. And then I used "Tab Key" which brought me to the "First name" field.
Once, My focus is available in the first field, I used action class to send my input to that field.
driver.get('file:///C:/Users/username/Documents/shadowDom.html')
driver.maximize_window()
ageElement = driver.find_element(By.ID, 'age')
ageElement.send_keys(30)
ageElement.send_keys(Keys.TAB)
actions = ActionChains(driver)
actions.send_keys("My name")
actions.perform()
sleep(10)
driver.quit()
Check the other post, how to interact with an element which is inside shadow dom [Open] tag.