Search code examples
javascriptpythonseleniumclicksendkeys

Key press with javascript python selenium


Is there a way to basically simulate key pressing from a keyboard?

I want to click an element that's typable and then mimic what an end-user would do to type, by pressing keys. I don't want to give any XPath and then use sendkeys or anything.

Bascially element.click() -> keypressing, I'm pretty sure selenium has no option for this that's why I'm turning to js. Does anyone know if something like this is possible?

EDIT: The test is done on a webpage

Can this be done?


Solution

  • First, you'll need to obtain the element (use XPath or CSS_Selector).

    You can accomplish this with ActionChains for instance if you want to copy/paste text use CTRL+'c' then CTRL+'v':

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.Chrome()
    
    driver.get('http://example.com')
    element = driver.find_element_by_xpath('the/xpath')
    
    ActionChains(driver).move_to_element(element).click(element).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()
    

    Or you can use ActionChains().send_keys()