Home > Back-end >  How to use keyboard events/keys in selenium webdriver on python
How to use keyboard events/keys in selenium webdriver on python

Time:07-17

In below code:-

  1. I am removing text from search field
  2. Then add a new order number in the search field
  3. Press Enter to start the search

First two steps happen fine but when the enter button code is triggered it types 323(appending in order number) in the search field and do nothing. I have tried many other keys as well but they all come as number no key function works through send_keys.

Below is the code for requirement mentioned above:-

import pytest
from curses import KEY_ENTER
from locale import normalize
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class TestFunc:
    
    order =""
    def test_validate_offer(self):
        username = "******"
        password = "*****"
        url = "http://*****"
        svc = Service("C:\\bin\\geckodriver.exe")
        driver = webdriver.Firefox(service=svc)
        pytest.order='3446'
        driver.implicitly_wait(15)
        driver.get("url")
        driver.find_element(By.ID,"login").send_keys(username)
        driver.find_element(By.ID,"password").send_keys(password)
        driver.find_element(By.XPATH,"//button[@type='submit']").click()
        
        driver.find_element(By.XPATH,"//div[@class='mk_apps_sidebar_panel']//li[2]//a[1]").click()
        driver.find_element(By.XPATH,"//i[@title='Remove']").click()
        driver.find_element(By.XPATH,"//input[@placeholder='Search...']").send_keys(pytest.order)
        wait = WebDriverWait(driver,10)
        search=wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "o_searchview_input")))
        search.send_keys(KEY_ENTER)
        
        sale_element=driver.find_element(By.XPATH,"//input[@placeholder='pytest.order']")
        sleep(5) 
        assert sale_element.text == pytest.order
        
        driver.close()

Any help appreciated.

CodePudding user response:

I think u have wrong import, try following:

from selenium.webdriver.common.keys import Keys
search.send_keys(Keys.RETURN)

CodePudding user response:

To press the Enter key instead of visibility_of_element_located() ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

from selenium.webdriver.common.keys import Keys

wait = WebDriverWait(driver,10)
search = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "o_searchview_input")))
search.click()
search.send_keys(Keys.ENTER)
  • Related