user989379
user989379

Reputation: 43

How to keyPress + click with selenium

I have a problem with my Selenium code not performing correctly the keyPress + click operation.

The test should open the jqueryui.com link and select the first 2 li elements on the page.

I am using Selenium 2.23 and Firefox 10. My code is as follows (I have trie 4 different ways to get it working but none performed):

FirefoxProfile profile = new FirefoxProfile();

profile.setEnableNativeEvents(true); WebDriver browser = new FirefoxDriver(profile); browser.get("http://jqueryui.com/demos/selectable/");

List elements = browser.findElements(By.cssSelector("ol#selectable li"));

 Actions a = new Actions(browser);      
 a.keyDown(Keys.CONTROL)
 .moveToElement(elements.get(0))
 .click()
 .moveToElement(elements.get(1))
 .click()
 .keyUp(Keys.CONTROL)
 .build()
 .perform();

    Keyboard keyboard = ((HasInputDevices) browser).getKeyboard();
    keyboard.pressKey(Keys.CONTROL);
    List<WebElement> selectOptions = browser.findElements(By.cssSelector("ol#selectable li"));
    selectOptions.get(1).click();
    selectOptions.get(3).click();
    keyboard.releaseKey(Keys.CONTROL); 
    Actions builder = new Actions(browser);
    builder.keyDown(elements.get(0), Keys.CONTROL)
        .click(elements.get(0))
        .click(elements.get(1))
        .keyUp(Keys.CONTROL);
    Action selectMultiple = builder.build();
    selectMultiple.perform();

    Robot robot = new Robot();
    robot.delay(1000);
    robot.keyPress(KeyEvent.CTRL_MASK);
    elements.get(0).click();
    elements.get(1).click();
    robot.keyRelease(KeyEvent.CTRL_MASK);

    browser.quit();

Can anyone help me with some other suggestions?

Upvotes: 4

Views: 12303

Answers (3)

Marcin Zmij
Marcin Zmij

Reputation: 11

I think that`s not a bug.

Try use this (C#):

Action builder = new Actions(driver);
builder.KeyDown(Keys.Control);
builder.Click(element1);
builder.Click(element2);
builder.KeyUp(Keys.Control);
builder.Perform();  

or for you(Java):

Actions a = new Actions(browser); a.keyDown(Keys.CONTROL) .moveToElement(elements.get(0)) .click() .moveToElement(elements.get(1)) .click() .keyUp(Keys.CONTROL) .build() .perform();

Just instead of

.Click(); .build(); .perform();

use

a.Click(YourWebElement);
a.keyUp(Keys.CONTROL);
a.build();
a.perform();

Should works,

Upvotes: 1

Oliver Bock
Oliver Bock

Reputation: 5115

This is a bug in Selenium, affecting shift/control/alt combined with clicks on Firefox for Windows. Star the bug and perhaps they will fix it.

Upvotes: 3

Petr Janeček
Petr Janeček

Reputation: 38444

I really have no idea why none of your attempts work (particularly the first one). The key constants are a mess.

Anyway, I have been able to make this work (on Windows XP):

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
elements.get(0).click();
elements.get(1).click();
robot.keyRelease(KeyEvent.VK_CONTROL);

Upvotes: 2

Related Questions