0

我正在尝试将包含 HTML 代码的字符串变量发送到位于框架内的文本框。HTML 代码如下所示:

<iframe id="rte" class="rteIfm" frameborder="0" contenteditable="" title="Description">
<html>
<head>
</head>
<body role="textbox" aria-multiline="true">
</body>
</html>
</iframe>

我尝试了两件事......首先,我尝试切换帧并使用萤火虫给我的x路径发送密钥:

 driver.SwitchTo().Frame(driver.FindElement(By.Id("rte")));
 driver.FindElement(By.XPath("/html/body")).SendKeys(myStringContainingHTML);

其次,我尝试将密钥发送到 ID 与框架相同的元素:

 driver.FindElement(By.Id("rte")).SendKeys(myStringContainingHTML);

在这两种情况下,都发生了同样的事情:起初,字符串(包含 HTML 代码)开始按预期输入到文本框中。然后在输入大约一个标签后,浏览器开始导航到不同的页面。我去了谷歌,开始在搜索框中输入内容,然后搜索字符串中的 HTML 代码块。

对我来说似乎很奇怪,我哪里出错了?

4

1 回答 1

0

我仍然不知道为什么会发生这种情况,但我使用它以编程方式将字符串复制到剪贴板并使用 WebDriver SendKeys() 将其传递过去的解决方法通常很简单:

Clipboard.SetText(myStringContainingHTML);
driver.FindElement(By.Id("myTxtBoxId")).SendKeys(OpenQA.Selenium.Keys.LeftControl + "v"); 

但实际上我在多线程时尝试这样做并得到错误:

 "Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

所以我不得不做这个解决方法只是为了把它放在剪贴板中:

class MyAsyncClass
{

static IWebDriver driver;

public static void MyAsyncMethod()
{
 FirefoxProfile myProfile = new FirefoxProfile();
 driver = new FirefoxDriver(myProfile);
 driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));

 STAClipBoard(myStringWithHtmlCode);
 driver.FindElement(By.Id("myTxtBoxId")).SendKeys(OpenQA.Selenium.Keys.LeftControl + "v"); 
}

 private static void STAClipBoard(string myStringWithHtmlCode)
 {
     ClipClass clipClass = new ClipClass();
     clipClass.myString = myString;
     System.Threading.Thread t = new System.Threading.Thread(clipClass.CopyToClipBoard);
        t.SetApartmentState(System.Threading.ApartmentState.STA);
        t.Start();
        t.Join();
    }


}//class

public class ClipClass
{
    public string myString;

    public void CopyToClipBoard()
    {
        Clipboard.SetText(description);
    }
}

}

于 2013-05-08T09:53:17.403 回答