selenium如何处理contenteditable=true

小卷 2011-12-14 2,715 views

一般对于输入框输入文本,我们都会采用type方法,比如:

selenium.type(“//div[@id=’CLYJ’]”, “werwerwqerqwer”);

但这个礼拜执行脚本的时候一直在这段不成功,之前一直把怀疑的焦点定位在弹出新窗口问题上,以为是新窗口没加载成功里面的内容,看网上答案也是很多说selenium对弹出框的支持不好,搜了很多资料,没有任何头绪,万般无奈,仔细的看了看这个文本框的实现方式,发现它并没有用最普遍的input写,而是<div id=”CLYJ” contenteditable=”true”></div>,和朋友交流了下,得知这是html5的实现方式,试着把这个文本框改写成了最简单的input方式,比如:

<input type=”text” tabindex=”2″ name=”shjl”>,脚本竟然跑通了!

由此看来这个type不了的问题应该不是新窗口的加载上,其实新窗口加载成功了,但tpye方法对这种contenteditable=true的文本框支持不好,立马去网上搜了下,发现果然很多人都遇到了同样的问题,但selenium官方网站对selenium rc的解决办法没有提供,但对webdriver的faq里有一个实现方法,原文是这么写的:
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();

仔细看((JavascriptExecutor) driver).executeScript(“document.body.innerHTML = ‘<br>'”);

它竟然使用了js直接插入,虽然一个是webdriver,一个是rc,
但既然webdriver的实现方式用了js插入,可见官方也确实知道了type方法对这种文本框不能处理,那我们何不在rc中也依样画葫芦,于是我们可以改成如下:
selenium.runScript(“var element= window.document.getElementById(‘CLYJ’);element.innerHTML=’xuyi’;”);
果然插入成功!


    欢迎拍砖!