0

I have below jQuery selector. I check it with data from the browser developer console.

jQuery("iframe#msg_body").contents().find("html body div span").text()

And I need to use this for cssSelector in selenium. for example as below format

By expectedOutput  = By.cssSelector(The_expression_I_need);

Can any one tell me how to do that ?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Piyum Rangana
  • 71
  • 1
  • 9
  • 3
    Are you sure your question is somehow related to `java`? – lealceldeiro May 08 '19 at 12:46
  • yes lealceldeiro – Piyum Rangana May 08 '19 at 12:47
  • Yes correct. issue is I cannot use it exactly as below jQuery("iframe#msg_body").contents().find("html body div span").text() – Piyum Rangana May 08 '19 at 12:50
  • 1
    You cannot do this via a CSS selector, as CSS does not cross frames. However it appears that Selenium does have alternative methods, such as this: https://stackoverflow.com/questions/24247490/find-elements-inside-forms-and-iframe-using-java-and-selenium-webdriver – Rory McCrossan May 08 '19 at 12:52
  • 1
    For first you need to move WebDriver to iframe: `driver.switchTo().frame("msg_body");` and after use WebDriver to find element and get the text: `driver.findElement(By.cssSelector("html/body/div/span")).getText();` – KunLun May 08 '19 at 12:54
  • 1
    @KunLun That is not a CSS selector. That is an XPath. – JeffC May 08 '19 at 13:16
  • 1
    @JeffC Ye, my bad. It should be `driver.findElement(By.xpath("html/body/div/span")).getText();` – KunLun May 08 '19 at 17:02

1 Answers1

1

As Rory McCrossan mentioned, You can't just access the element using CSS selector since it is inside an iframe.

You have to switch to the iframe and search for the element.

new WebDriverWait(driver,30).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("msg_body"));
By expectedOutput = By.cssSelector("html body div span");

Then you can get the element using the locator.

The locator will return all the span tag inside a div tag inside the body tag. So I'm guessing it will most probably get more than one element.

S Ahmed
  • 1,454
  • 1
  • 8
  • 14