iframe 内的 selenium webdriver 元素是可点击的,但 moveToElement 会导致 MoveTargetOutOfBoundsError元素、selenium、ifram

2023-09-07 23:27:39 作者:良人

我有一个带有 iframe 的页面.iframe 内部是一个表格.当用户将鼠标移到该表上时,会出现一些元素.我想点击其中一个元素.

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.

我认为我的一些第一步应该是选择 iframe,然后选择 moveToElement(table).但这会导致 MoveTargetOutOfBoundsError.

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

奇怪的是我能够选择 iframe 并点击表格.点击不会抱怨元素的 x,y 坐标,但 moveToElement 会抱怨.为什么?(不幸的是,单击表格执行的操作会导致我想消失的那些按钮,所以这不是一个选项.)

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.)

我怎样才能完成我想要的(选择 iframe、将鼠标悬停在表格上、等待按钮出现、单击其中一个按钮)?

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

版本信息:

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'

点击表格成功的java代码如下:

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();

这是抱怨表位置的java代码:

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()

推荐答案

我认为你必须滚动到视图中:

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());
}