Selenium WebDriver - KeyPress并同时点击C#

时间:2013-03-07 14:22:02

标签: selenium webdriver automated-tests selenium-webdriver

如何在selenium WebDriver 2中同时执行两项操作? 我需要按住CTRL并单击链接。我想在C#中看到一些解决方案。

这不起作用。

Actions builder = new Actions(_driver);
builder.SendKeys(Keys.Control).Click(link).KeyUp(Keys.Control);
IAction multiple = builder.Build();
multiple.Perform();

非常感谢答案

2 个答案:

答案 0 :(得分:1)

您忽略了构建器的返回值。尝试:

Actions builder = new Actions(_driver);
builder = builder.KeyDown(Keys.Control).Click(link).KeyUp(Keys.Control);
IAction multiple = builder.Build();
multiple.Perform();

甚至是这个的等效简写:

new Actions(_driver)
    .KeyDown(Keys.Control)
    .Click(link)
    .KeyUp(Keys.Control)
    .Perform();

答案 1 :(得分:0)

如果你无法使Actions工作,你可以拯救并调用javascript(或jQuery,如我的例子中所示),以调用 Ctrl-Click

示例html片段(您尝试自动化测试)...

<script type='text/javascript'>
    function myClick(e) {if(e.ctrlKey) {alert('ctrl+click');}}
</script>

...

<img id='myElement' onclick='myClick();' src='abc.gif' />

示例c#call:

public void ExecuteJs(string javascript)
{
    var js = Browser.WebDriver as IJavaScriptExecutor;
    if (js != null) js.ExecuteScript(javascript);
}

public void CtrlClickElement(string elementId)
{
    var script = string.Format("var e=jQuery.Event('click');e.ctrlKey=true;$('#{0}').trigger(e);", elementId);
    ExecuteJs(script);
}

...

CtrlClickElement("myElement");

参考: