Reputation: 694
I am trying to use Playwright to get contents of the open shadow root element which looks like this.
<some-element>
#shadow-root
ABC
</some-element>
Here #shadow-root
contains text ABC
without any additional tags.
I am able to locate some-element
but I cannot find a way to get the contents of #shadow-root
Example Python code I am using is below:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.firefox.launch(args=["--disable-gpu"], headless=False)
page = browser.new_page()
page.goto("https://www.sample.com")
some_element = page.locator('some-element')
...
# ???
Playwright docs state that their selectors can choose elements in shadow DOM, but examples contain only options where shadow-root
contains other tags.
How do I get the contents of #shadow-root
if it only contains the text, without any tags ?
Upvotes: 3
Views: 5654
Reputation: 1654
I tried with a demo page that has the same behavior that your page has: https://googlechromelabs.github.io/shadow-selection-polyfill/demo.html
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(args=["--disable-gpu"], headless=False)
page = browser.new_page()
page.goto("https://googlechromelabs.github.io/shadow-selection-polyfill/demo.html")
print(page.evaluate("document.querySelector('#host1').shadowRoot.childNodes[0].data"))
Upvotes: 0
Reputation: 21695
The locator will help you find an element. But from there, if you don't have an element to pierce the Shadow DOM, you might need to do that manually.
text = page.locator('some-element').first.evaluate("node => node.shadowRoot.innerHTML")
Upvotes: 2