当我单击链接时,会打开一个弹出窗口,我可以在其中填写一些字段。但是,此弹出窗口包含一个 Iframe,其中包含我想要在测试中使用的字段。问题是我似乎无法切换到 iFrame 来访问字段。
我首先尝试了以下方法,但这会导致 (org.openqa.selenium.NoSuchElementException: 无法定位元素: {"method":"xpath","selector":"/html/body/iframe"}):
driver.switchTo().frame(driver.findElement(By.xpath("/html/body/iframe")));
然后我尝试了以下操作,这似乎通过了 iFrame 但导致了 (org.openqa.selenium.TimeoutException: 等待元素可点击 15 秒后超时:By.id://div[@class= 'actionbutton-content 不可选择']) 和 (NoSuchElementException: 无法定位元素: {"method":"id","selector":"//div[@class='actionbutton-content unselectable']"}):
driver.switchTo().frame(0);
wait.until(ExpectedConditions.elementToBeClickable(By.id("//div[@class='actionbutton-content unselectable']")));
这是页面源代码的第一部分:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Page title</title>
<script src="scripts/JQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
script here....
</script>
</head>
<body MS_POSITIONING="GridLayout" leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0">
<input type="hidden" id="newxObjectID"> <input type="hidden" id="newxObjectName"/>
<iframe height="100%" width="100%" frameborder="0" scrolling="no" src="fxeditobject.aspx?function=showobjectfields&key=0x3928x0x60937x&viewid=&callerwindow=true&fieldDefId=0&defid=3928" >
#document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html webdriver="true">
<head></head>
<body id="PageBody" onload="" etc. etc. etc. >
**Fields I'm looking for are somewhere in this area**
</iframe>
</body>
最佳答案
您是否尝试过稍微不同的 xpath? -> 双斜杠"//html/body/iframe"
driver.switchTo().frame(driver.findElement(By.xpath("//html/body/iframe")));
如果这不起作用,可能 iframe 没有直接位于您的 body 标记下(您是否发布了完整的 html 或片段?),那么您可以在 iframe 前面添加另一个双斜杠:
driver.switchTo().frame(driver.findElement(By.xpath("//html/body//iframe")));
至于你的第二个问题:
如果您提供 xpath 表达式,您还应该搜索 By.xpath(您搜索了 By.id):
driver.switchTo().frame(0);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='actionbutton-content unselectable']")));
关于java - 无法使用 Eclipse 和 Selenium webdriver Java 定位并切换到 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170211/