我想选择一个 Iframe 并在 Body 中输入值。我正在尝试使用下面的代码。
HTML 代码:
<iFrame id="4564654_content_ifr">
<html>
<head>
<body id="tiny">
<div aria-lable="New Compose body">
<br>
</div>
</body>
</head>
</html>
</iFrame>
Selenium 代码:
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'content_ifr')]")));
driver.findElement(By.xpath("//*[@id='tiny']/div[1]")).sendKeys("Happy New IFrame");
但我无法输入值。
有人可以帮我解决这个问题吗?
最佳答案
您可以直接设置innerHTML
,而不是发送 key 。
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);
如果您正在测试某种所见即所得编辑器(例如 TinyMCE),请随时查看本文:
Test WYSIWYG editors using Selenium WebDriver
然后您也许可以直接通过编辑器的API设置内容。已知 Firefox 中的 sendKeys
存在问题,但 Chrome 或 PhantomJS 应该没问题。
关于java - 如何使用 Selenium WebDriver 选择新的 IFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489986/