vitaliis
vitaliis

Reputation: 4212

Finding shadow DOM text with Selenium and CSS

I am trying to locate an input text from input field that is saved in shadow DOM with:

driver.find_element_by_css_selector("#my_id div:nth-of-type(2)").text 

but it does not help. HTML part

<input _ngcontent-c21="" class="clr-input ng-untouched ng-pristine ng-valid" id="my_id" name="my_id" placeholder="My placeholder namespace" size="40" type="text">
 #shadow-root {user-agent}
  <div pseudo="-webkit-input-placeholder" id="placeholder" style="display: none !important;">My placeholder namespace</div>
  <div>Text I need to find</div>

Also tried this with not luck:

shadow_section = driver.execute_script('''return 
document.querySelector("#my_id").shadowRoot''')
            print(shadow_section.find_element_by_css_selector("div:nth-of-type(2)").text)

What is the best approach for finding elements in shadow DOM in this case? In my case locator should be linked to element.

Update: as suggested I tried:

  shadow_root = driver.execute_script('return arguments[0].shadowRoot', driver.find_element_by_css_selector("#my_id"))
  shadow_root_element = shadow_root(driver.find_element_by_css_selector('div:nth-child(2)'))

But received:

TypeError: 'NoneType' object is not callable

on shadow_root_element row.

Upvotes: 1

Views: 2497

Answers (2)

vitaliis
vitaliis

Reputation: 4212

I was not able to find a solution with Javascripts .shadowRoot option and it is a mystery for me why it does not work. This option works just fine. It input text:

driver.find_element_by_css_selector("#my_id").get_attribute("value")

or

driver.find_element_by_id("my_id").get_attribute("value")

I am still very interested in the approach proposed by PDHide.

Upvotes: 1

PDHide
PDHide

Reputation: 19989

element=driver.execute_script(
    "return document.querySelector('#my_id').shadowRoot.querySelector('div:nth-child(2)')")

you have to use execute script to find shadow root, the element will have the item you want. You can now use element.text to get the text

Upvotes: 1

Related Questions