Passing button keys in automation selenium

I want to pass keys in automations like (Control+W)

1 Like

You could use sendkeys method for doing that. For example: driver.find_element_by_tag_name(‘body’).send_keys(Keys.CONTROL + ‘w’)

1 Like

Another method that you can use is ActionChains(). It is used to automate low-level interactions for automation testing with Selenium, such as key press, mouse button actions, etc.

For example, In order to refresh the webpage, we make use of the ‘CTRL + F5’ combination.

import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

'''Creation of Firefox Webdriver '''
# driver = webdriver.Chrome()
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com/")

time.sleep(5)

print("Before refresh")

ActionChains(driver) \
    .key_down(Keys.CONTROL) \
    .send_keys(Keys.F5) \
    .key_up(Keys.CONTROL) \
    .perform()

print("After refresh")

sleep(5)
driver.quit()

The main advantage of using this is that you can automate any combination of keyboard/mouse press/click, whatsoever.

1 Like