Selenium and iframe

2019-03-12 05:16发布

问题:

I have an iframe that gets loaded when i click on a tab on a page. When i use Firebug to look at the iframe on IE8, all i see is:

iframe id=tabContextFrame class=contextFrame contentEditable=inherit src=/xyz.dt?forward=show&layouttype=NoHeader&runid=1234 name=tabContextFrame url=/xyz.dt?forward=show&layouttype=NoHeader&runid=1234 scrolling=auto

and that's it.The hierarchy below the iframe can't be seen. I want to click on a link within the iframe. To find the elements within the iframe, I did a selenium.click("on the tab that loads the iframe") and then selenium.getHtmlSource(). From this source, I can at least locate my link of interest. I did a selenium.click("//span[text()='Link']") but it doesn't seem to do anything. Any ideas please?

Here is the code:

selenium.click("//span[text()='tab that loads iframe']");   
Thread.sleep(5000);   
selenium.selectFrame("tabContextFrame");         
selenium.mouseOver("//span[text()='Link']");   
selenium.mouseDown("//span[text()='Link']");  
selenium.mouseUp("//span[text()='Link']");   
Thread.sleep(5000);   
selenium.selectFrame("null");  

回答1:

I'm guessing you are using Selenium 1.0. Have you looked at Selenium 2.0 and WebDriver. I found the following and it worked for me:

Q: How do I type into a contentEditable iframe? A: Assuming that the iframe is named "foo":

driver.switchTo().frame("foo");
WebElement editable = driver.switchTo().activeElement(); 
editable.sendKeys("Your text here"); 

Sometimes this doesn't work, and this is because the iframe doesn't have any content. On Firefox you can execute the following before "sendKeys":

((JavascriptExecutor) driver).executeScript("document.body.innerHTML = '<br>'"); 

This is needed because the iframe has no content by default: there's nothing to send keyboard input to. This method call inserts an empty tag, which sets everything up nicely.

Remember to switch out of the frame once you're done (as all further interactions will be with this specific frame):

driver.switchTo().defaultContent();

I found this on http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions



回答2:

Use driver.switchTo().defaultContent(); first then do your operation