Search code examples
pythonselenium-webdriverwebdriversendkeysctrl

How Can I Simultaneously Press Ctrl + A While Using Python Selenium?


I am using action chains and lines like the following:

actions.click(elementimclickingon).send_keys(Keys.CONTROL + "A").perform()

I have subsequent actions in the above line before, like .pause(1).send_keys(myvariablestring), but that didn't seem relevant here.

Regardless of the above, this does not work as the keys do not appear to be sent simultaneously.

I’ve already tried the code above, but it doesn't seem to send Ctrl + A simultaneously. The outcome I'm going for is just to send a "select all" command.


Solution

  • To achieve that, you need to use key_down and key_up methods to press and release the keys in the correct chain order:

    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.keys import Keys
    
    ...
    
    actions = ActionChains(driver)
    actions.click(elementimclickingon).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform()
    

    Here is a full minimal example to select all text with Ctrl + A and copy it with Ctrl + C:

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Edge()
    driver.get("http://www.example.com")
    
    element = driver.find_element(By.TAG_NAME, "body")
    
    actions = ActionChains(driver)
    # Ctrl + A
    actions.click(elementimclickingon).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform()
    # Ctrl + C
    actions.key_down(Keys.CONTROL).send_keys("c").key_up(Keys.CONTROL).perform()
    
    driver.quit()
    

    If you only want to send a "select all" command, you can use JavaScript for that with execute_script like this:

    driver.execute_script("document.execCommand('selectAll')")