使用C#与selenium和cleditor
我希望能够在c#中使用selenium为cleditor文本字段设置正文,但这个过程似乎非常困难。 任何人都可以像我4岁那样解释它吗?
基本的Selenium逻辑是您首先找到元素,然后对其执行操作。
但是,在这种情况下,您有以下困难:
- 编辑器在
iframe
- iframe没有id,name甚至有意义的src
- 编辑器不是输入或文本区域,而是
body
本身。
如何导航到iframe (Arran的链接应该是一个很好的教程,看看)
使用Firefox + Firebug + Firepath查找iframe。
如您所见,页面中有四个iframe,您需要使用以下方法之一切换到编辑器框架,而不是其他框架。 ( 来源 )
IWebDriver Frame(int frameIndex); // works but not desirable, as you have 4 frames, index might be changing IWebDriver Frame(string frameName); // not working, your editor doesn't have frameName or id. IWebDriver Frame(IWebElement frameElement); // the way to go, find frame by xpath or css selector in your case
所以我们有:
IWebElement iframe = driver.FindElement(By.XPath("//iframe[@src='javascript:true;']")); driver.SwitchTo().Frame(iframe);
如何将密钥发送到编辑器
一旦你的驱动程序在iframe中,通过Firebug,你可以看到编辑器实际上是body
,而不是input
或textarea
。
所以你需要找到body元素,清除它并发送密钥。 请注意, Clear()
可能不适用于body元素,因此您需要使用IJavaScriptExecutor
或发送Control+a
来首先选择所有。
切换出iframe
将一些文本发送到编辑器后,可以使用driver.SwitchTo().DefaultContent();
出去
完成的代码
using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; namespace SOTest { [TestClass] public class TestCLEditor { [TestMethod] public void TestMethod1() { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://premiumsoftware.net/CLEditor"); // find frames by src like 'javascript:true;' is really not a good idea, but works in this case IWebElement iframe = driver.FindElement(By.XPath("//iframe[@src='javascript:true;']")); driver.SwitchTo().Frame(iframe); IWebElement body = driver.FindElement(By.TagName("body")); // then you find the body body.SendKeys(Keys.Control + "a"); // send 'ctrl+a' to select all body.SendKeys("Some text"); // alternative way to send keys to body // IJavaScriptExecutor jsExecutor = driver as IJavaScriptExecutor; // jsExecutor.ExecuteScript("var body = document.getElementsByTagName('body')[0]; body.innerHTML = 'Some text';"); driver.Quit(); } } }
在谷歌浏览器中,导航到页面右键单击文本字段的可编辑区域。 单击“检查元素”。 打开html后,右键单击突出显示的元素,然后单击Copy XPath。
在Selenium Web驱动程序中
IWebElement textField = driver.FindElement(By.XPath("Paste what you got from CHROME")); textField.SendKeys("Desired Text");