How to select new IFrame using Selenium WebDriver?

2019-03-03 13:06发布

问题:

I wanted to select an Iframe and Enter values in the Body . I am trying with the below code.

HTML code:

 <iFrame id="4564654_content_ifr">
     <html>
       <head>
         <body id="tiny">
             <div aria-lable="New Compose body">
                 <br>
             </div>
         </body>
       </head>
      </html>
  </iFrame>

Selenium code:

    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'content_ifr')]")));
driver.findElement(By.xpath("//*[@id='tiny']/div[1]")).sendKeys("Happy New IFrame");

But I could not able to enter values.

Can anybody help me with this?

回答1:

Instead of sending keys, you can set innerHTML directly.

driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'content_ifr')]")));

WebElement body = driver.findElement(By.cssSelector("body"));
(JavascriptExecutor)driver.executeScript("arguments[0].innerHTML = 'Happy New IFrame'", body);

If you are testing some kind of WYSIWYG editors like TinyMCE, feel free to have a look at this article:

Test WYSIWYG editors using Selenium WebDriver

Then you might be able to set content through editor's API directly. It's known to have issues with sendKeys in Firefox, but should be fine with Chrome or PhantomJS.



回答2:

Try the below May help you.

WebElement sg= driver.findElement(By.xpath("//iframe[@id='4564654_content_ifr']"));
                driver.switchTo().frame(sg);


回答3:

List<WebElement> iframeElements= driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " + iframeElements.size());
driver.switchTo().frame(0);
Thread.sleep(3000);
System.out.println("it is on frame1");