简体   繁体   中英

Key press in (Ctrl + mouse click) in Selenium WebDriver using java

I need to press control+mouse click keys using Selenium WebDriver(java). I need to select multiple element in my script. Is there any way to do it?

I checked the Selenium libraries and found that selenium allows key press of special and functional keys only.

There is already written library Actions in WebDriver which you can use.

Short Description of what is happening:

First you are pressing the Control button and then you are clicking (in this case) 3 times on your defined WebElemen objects) then your are unpressing the Control and finish your Actions.

In this case you can achive the selection of 3 items (or opening a 3 new tabs) depending on what your WebElements are.

Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
    .click(first_WebElement)
    .click(second_WebElement)
    .click(third_WebElement)
    .keyUp(Keys.LEFT_CONTROL)
    .build()
    .perform();

Do it with the help of 'Actions' as below:

Actions action=new Actions(driver);
action.keyDown(Keys.CONTROL).build().perform();
driver.findElement(By.xpath(".//*[@id='selectable']/li[1]")).click();
driver.findElement(By.xpath(".//*[@id='selectable']/li[3]")).click();
action.keyUp(Keys.CONTROL).build().perform();

You achieve same using jquery code

JavascriptExecutor js = (JavascriptExecutor) driver;  
String script = "e = jQuery.Event('click');e.ctrlKey = true;    $('secondRow_Css_locator').trigger(e);";
js.executeScript(script);

OR you can also use robot class but it can lock your screen for a moment

 Robot robot = new Robot();
 robot.keyPress(KeyEvent.VK_CONTROL);
 robot.keyRelease(KeyEvent.VK_CONTROL);
 robot.mousePress(InputEvent.BUTTON1_MASK);
 robot.mouseRelease(InputEvent.BUTTON1_MASK);

As of 2018 the is the first results pops up. Earlier it was working fine after FF 61 (direct jump form 47 to 61) It starts breaking. unfortunately none of the answer worked for me. Solved it by action.keyDown(Keys.CONTROL).click(myWebElements.get(i)).keyUp(Keys.CONTROL).perform(); just iterating every element one by one

In the case of using Mac, te code would be next:

action.keyDown(Keys.COMMAND)
            .click(WebElement)
            .keyUp(Keys.COMMAND)
            .build()
            .perform();

it worked with me using this:

Actions action=new Actions(driver);
action.keyDown(Keys.CONTROL).build().perform();
driver.findElement(By.xpath(".//*[@id='selectable']/li[1]")).click();
driver.findElement(By.xpath(".//*[@id='selectable']/li[3]")).click();
action.keyUp(Keys.CONTROL).build().perform();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM