Search code examples
pythonseleniumautomationkeyboardarrow-keys

How to simulate pressing the arrow down key when a specific element is present in the HTML using Selenium and Python


I want python to click on a key on my keyboard for example the arrow down key when a specific word for example google is present somewhere in the browser or in the searh bar. Is it possible with selenium or the os module. Any suggestions?


Solution

  • Using Selenium to click on the Arrow Down key when a specific condition is met, as an example I have demonstrated through the following steps:

    • Open the url https://www.google.com/
    • Wait for the Google Home Page search box element i.e. By.NAME, "q" to be clickable.
    • Sends the character sequence selenium.
    • Wait for the auto suggestions to be visibile.
    • Click twice on Arrow Down key.

      • Code Block:

        from selenium import webdriver
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.common.keys import Keys
        
        options = webdriver.ChromeOptions() 
        options.add_argument("start-maximized")
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
        driver.get('https://www.google.com/')
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("Selenium")
        WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul[role='listbox'] li")))
        driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
        driver.find_element_by_css_selector('body').send_keys(Keys.DOWN)
        
      • Browser Snapshot:

    Keys.DOWN

    PS: Implementing the above logic you can also click on Arrow Up, Arrow Left and Arrow Right keys.