selenium webdriver element inside iframe is clicka

2019-06-08 22:38发布

问题:

I have a page with an iframe. Inside the iframe is a table. When the user moves the mouse over this table, some elements appear. I'd like to click one of those elements.

I think some of my first steps should be to select the iframe, and then moveToElement(table). But this results in a MoveTargetOutOfBoundsError.

The strange thing is that I'm able to select the iframe and click on the table. The click doesn't complain about the element's x,y coordinates but moveToElement complains. Why? (Unfortunately clicking on the table performs an action which causes those buttons I want to disappear so this is not an option.)

And how can I accomplish what I want (select iframe, hover over table, wait for buttons to appear, click one of the buttons)?

version info:

Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 15:53:30'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.6.0_37'

Here's the java code that succeeds in clicking the table:

driver.switchTo().defaultContent();
driver.switchTo().frame("frameId");
WebElement e = driver.findElement(By.id("foo"));
e.click();

Here's the java code that complains about the location of the table:

driver.switchTo().defaultContent();
driver.switchTo().frame("frameId");
WebElement e = driver.findElement(By.id("foo"));
Actions builder = new Actions(driver);
builder.moveToElement(e).build().perform(); // error happens in moveToElement()

回答1:

I think you have to scroll into view:

if (element instanceof Locatable) {
    Locatable remoteElement = (Locatable) inputElement;          
    remoteElement.getLocationOnScreenOnceScrolledIntoView();
}

If you want to hover on an element, you have to extend the above a bit:

if (element instanceof Locatable) {
    Locatable hoverItem = (Locatable) element;
    hoverItem.getLocationOnScreenOnceScrolledIntoView();
    Mouse mouse = ((HasInputDevices) webDriver).getMouse(); 
    mouse.mouseMove(hoverItem.getCoordinates());
}