How to select new IFrame using Selenium WebDriver?

2019-03-03 13:08发布

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?

3条回答
看我几分像从前
2楼-- · 2019-03-03 13:13

Try the below May help you.

WebElement sg= driver.findElement(By.xpath("//iframe[@id='4564654_content_ifr']"));
                driver.switchTo().frame(sg);
查看更多
在下西门庆
3楼-- · 2019-03-03 13:27
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");
查看更多
贪生不怕死
4楼-- · 2019-03-03 13:34

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.

查看更多
登录 后发表回答