Accessing Shadow DOM tree with Selenium

后端 未结 9 814
执念已碎
执念已碎 2020-11-28 09:57

Is it possible to access elements within a Shadow DOM using Selenium/Chrome webdriver?

Using the normal element search methods doesn\'t work, as is to be expected.

9条回答
  •  失恋的感觉
    2020-11-28 10:28

    I am using C# and Selenium and managed to find an element inside a nestled shadow DOM using java script. This is my html tree:

    html tree

    I want the url on the last line and to get it I first select the "downloads-manager" tag and then the first shadow root right below it. Once inside the shadow root I want to find the element closest to the next shadow root. That element is "downloads-item". With that selected I can enter the second shadow root. From there I select the img item containing the url by id = "file-icon". At last I can get the attribute "src" which contains the url I am seeking.

    The two lines of C# code that does the trick:

    IJavaScriptExecutor jse2 = (IJavaScriptExecutor)_driver;
    var pdfUrl = jse2.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.getElementById('file-icon').getAttribute('src')");
    

提交回复
热议问题