Sameera De Silva
2 min readMay 27, 2022

--

Does it need to capture #dcoument which locate below in iframe when capturing locators using CSS locators for Selenium WebDriver?

I have below DOM structure, since it’s inside of a Shadow DOM, I am using CSS locators to capture the elements.

I want to access html tag which below the iframe , but as per the DOM tree structure., it’s inside of #dcoument, so do I need to go to #dcoument ?

Answer-

First capture the iframe using the element above it .

This is the element above the iframe.

WebElement sn_polaris_layout=sn_canvas_appshell_root.findElement(By.cssSelector("sn-polaris-layout"));// So had to use css , here passes tag name.

// Using sn_polaris_layout, capture the iframe using tag.

WebElement iframe=sn_canvas_appshell_root.findElement(By.cssSelector("iframe"));// Tag is used

Then, there is #document but no need to capture it, simply switch to the iframe.

driver.switchTo().frame(iframe);

Since now inside of iframe using class can capture the elements inside of it.

WebElement html=driver.findElement(By.cssSelector("html[class='ltr date-calendar tabbed']"));// Class is used

Full code is as per below.

WebElement sn_polaris_layout=sn_canvas_appshell_root.findElement(By.cssSelector("sn-polaris-layout"));// So had to use css , here passes tag name.
// Using sn_polaris_layout, capture the iframe tag.(title=Main Content)
WebElement iframe=sn_canvas_appshell_root.findElement(By.cssSelector("iframe"));// Tag is used
driver.switchTo().frame(iframe); // There is #document but no need to capture it, simply switch to the iframe.
// Since now inside of iframe using class can capture the elements inside of it,
WebElement html=driver.findElement(By.cssSelector("html[class='ltr date-calendar tabbed']"));// Class is used

--

--