为什么使用WebDriver's SendKeys()发送带有HTML标签的字符串会导致浏览器导航到随机页面?
本文关键字:字符串 标签 浏览器 导航 随机 HTML WebDriver SendKeys 为什么 | 更新日期: 2023-09-27 18:12:22
我试图将包含HTML代码的字符串变量发送到位于框架内的文本框。HTML代码看起来像这样:
<iframe id="rte" class="rteIfm" frameborder="0" contenteditable="" title="Description">
<html>
<head>
</head>
<body role="textbox" aria-multiline="true">
</body>
</html>
</iframe>
我试过两件事……首先,我尝试切换帧并使用firebug给我的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代码块。
对我来说似乎很奇怪,我哪里出错了?
我仍然不知道为什么会发生这种情况,但我正在使用它的解决方案,以编程方式将字符串复制到剪贴板,并通过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);
}
}
}